我正在尝试编写一个接受两个用户输入的函数:一个单词和一个最大长度。该函数从一个文本文件(在程序前面打开)中读取,查看所有符合给定最大长度的单词,并从文件中返回一个单词列表,其中包含用户给出的单词中的所有字母.到目前为止,这是我的代码:
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
此代码有效,但我的问题是它没有考虑从文件中读取的单词中的重复字母。例如,如果我输入“GREEN”作为 otherWord,则该函数返回一个包含字母 G、R、E 和 N 的单词列表。我希望它返回一个包含具有 2 个 E 的单词的列表。我想我还必须对 letterCount 部分进行一些调整,因为重复项会影响它,但我现在更关心识别重复项。任何帮助将不胜感激。
最佳答案
您可以为 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)
您也可以使用 Python 的 for..else 构造在没有 match
变量的情况下编写此代码:
if len(line) <= int(maxLength):
for l, c in counter.items():
if line.count(l) < c:
break
else:
listOfWords.append(line)
编辑:如果您想在字符数上进行精确匹配,请改为检查是否相等,并进一步检查是否有任何额外的字符(如果行长度不同就是这种情况)。
关于python - 比较两个字符串,包括重复的字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15373339/