比较两个字符串,包括重复字母吗?

3 投票
2 回答
3304 浏览
提问于 2025-04-17 18:52

我正在尝试写一个函数,这个函数需要两个用户输入:一个单词和一个最大长度。这个函数会从一个之前打开的文本文件中读取内容,查看所有符合最大长度的单词,并返回一个包含用户输入单词所有字母的单词列表。以下是我目前的代码:

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”作为其他单词,那么这个函数返回的单词列表只包含字母 G、R、E 和 N。我希望它能返回一个包含两个 E 的单词列表。我想我还需要对字母计数的部分进行一些调整,因为重复字母会影响这个部分,但现在我更关心的是如何识别重复字母。任何帮助都将非常感激。

2 个回答

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]
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)

你也可以不使用 match 变量,直接用 Python 的 for..else 结构来写:

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

补充一下:如果你想要字符数量完全相同,可以检查它们是否相等,并进一步检查是否有多余的字符(如果行的长度不同,就会出现这种情况)。

撰写回答