3

単語と最大長の2つのユーザー入力を受け取る関数を作成しようとしています。この関数は、テキストファイル(プログラムの前半で開いたもの)から読み取り、指定された最大長内に収まるすべての単語を調べ、ユーザーが指定した単語のすべての文字を含むファイルから単語のリストを返します。 。これまでの私のコードは次のとおりです。

def comparison():
    otherWord = input("Enter word: ")
    otherWord = list(otherWord)
    maxLength = input("What is the maximum length of the words you want: ")
    listOfWords = []
    for line in file:
        line = line.rstrip()
        letterCount = 0
        if len(line) <= int(maxLength):
            for letter in otherWord:
                if letter in line:
                    letterCount += 1
            if letterCount == len(otherLine):
                listOfWords.append(line)
    return listOfWords

このコードは機能しますが、私の問題は、ファイルから読み取られた単語の重複文字が考慮されていないことです。たとえば、otherWordとして「GREEN」と入力すると、関数は文字G、R、E、およびNを含む単語のリストを返します。2つのEを含む単語を含むリストを返したいと思います。重複がそれに影響を与えるので、私もletterCount部分を微調整する必要があると思いますが、今のところ重複を認識することにもっと関心があります。どんな助けでも大歓迎です。

4

2 に答える 2

2

otherWord次のように、のカウンターを使用できます。

>>> from collections import Counter
>>> otherWord = 'GREEN'
>>> otherWord = Counter(otherWord)
>>> otherWord
Counter({'E': 2, 'R': 1, 'N': 1, 'G': 1})

そして、あなたの小切手は次のようになります:

if len(line) <= int(maxLength):
    match = True
    for l, c in counter.items():
        if line.count(l) < c:
            match = False
            break
    if match:
        listOfWords.append(line)

matchPythonのfor..else構文を使用して、変数なしでこれを記述することもできます。

if len(line) <= int(maxLength):
    for l, c in counter.items():
        if line.count(l) < c:
            break
    else:
        listOfWords.append(line)

編集:文字数を完全に一致させたい場合は、代わりに等しいかどうかを確認し、さらに余分な文字があるかどうかを確認します(行の長さが異なる場合)。

于 2013-03-12T22:24:11.247 に答える
0

collections.Counterを使用して、(マルチ)セット操作を実行することもできます。

In [1]: from collections import Counter

In [2]: c = Counter('GREEN')

In [3]: l = Counter('GGGRREEEENN')

In [4]: c & l  # find intersection
Out[4]: Counter({'E': 2, 'R': 1, 'G': 1, 'N': 1})

In [5]: c & l == c  # are all letters in "GREEN" present "GGGRREEEENN"?
Out[5]: True

In [6]: c == l  # Or if you want, test for equality
Out[6]: False

したがって、関数は次のようになります。

def word_compare(inputword, wordlist, maxlenght):
    c = Counter(inputword)
    return [word for word in wordlist if maxlenght <= len(word) 
                                      and c & Counter(word) == c]
于 2013-03-12T22:22:18.647 に答える