Inquiries about code correction related to English word extraction

Asked 1 years ago, Updated 1 years ago, 312 views

Hello, I'm a beginner at studying Python. I'm asking you a question to find out the answer because there's something I'm not sure about while I'

If I modify the range after the split on the word side, an error appears and what should I do?

def filter_by_text(text) :
    corpus = []
    with open('corpus.txt') as file:
        for tuple in file:
            word = tuple.strip().split('/')[0]
            freq = int(tuple.split('/')[1])
            if word[0] == text:
                new_corpus=(word,freq)
                corpus.append(new_corpus)

    print(sorted(corpus, key=lambda x:x[1], reverse=True)[:20])

t = input()
filter_by_text(t)

python coding

2022-12-19 19:52

1 Answers

def filter_by_text(text) :
    corpus = []
    with open('corpus.txt') as file:
        for tuple in file:
            word = tuple.strip().split('/')[0]
            freq = int(tuple.split('/')[1])
            new_corpus=(word,freq)
            corpus.append(new_corpus)

    result = []
    for tuple in corpus:
        wording = tuple[0]
        if wording.startswith(text):
            result.append(text)

    print(sorted(result, key=lambda x:x[1], reverse=True)[:20])

t = input()
filter_by_text(t)


2022-12-20 08:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.