仅打印列表中包含其他列表中字符的单词?

时间:2019-04-16 20:29:45

标签: python python-3.x

我正在研究一个有趣的小问题,它是由朋友发送给我的。问题需要我用文本文件中的常用单词填充数组,然后打印此列表中包含用户提供的某些字符的所有单词。我可以填充我的数组没有问题,但是似乎实际上比较两个列表的代码部分无法正常工作。下面是我编写的用于比较两个列表的函数。

#Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
    #Prompt user for list of letters and convert that string into a list of characters
    string = input("Enter your target letters: ")
    letterList = list(string)
    #For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
    for word in wordList:
        matchCount = 0
        for char in word:
            if char in letterList:
                matchCount+=1
            #If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
            if matchCount == len(word):
                matchList.append(word)
    print(matchList)

代码运行得很好,我没有收到任何错误输出,但是一旦用户输入了他们的字母列表,就什么也不会发生。为了测试,我尝试了一些与我在wordList中已知的单词匹配的输入(例如添加,斧头,树等)。但是输入字母字符串后,什么也不会打印。

这就是我填充wordList的方式:

def readWords(filename):
    try:
        with open(filename) as file:
            #Load entire file as string, split string into word list using whitespace as delimiter
            s = file.read()
            wordList = s.split(" ")
            getLetters()
    #Error handling for invalid filename. Just prompts the user for filename again. Should change to use ospath.exists. But does the job for now
    except FileNotFoundError:
        print("File does not exist, check directory and try again. Dictionary file must be in program directory because I am bad and am not using ospath.")
        getFile()

编辑:更改了将循环计数重置为0的功能,然后才开始循环字符,但仍无输出。

2 个答案:

答案 0 :(得分:0)

编辑:添加一个全局声明以从函数内部修改列表:

wordList = [] #['axe', 'tree', 'etc']
def readWords(filename):
    try:
        with open(filename) as file:
            s = file.read()
            global wordList  # must add to modify global list
            wordList = s.split(" ")
    except:
        pass

这是一个有效的示例:

wordList = ['axe', 'tree', 'etc']


# Function that prompts user for the set of letters to match and then compares that list of letters to each word in our wordList.
def getLetters():
    # Prompt user for list of letters and convert that string into a list of characters
    string = input("Enter your target letters: ")
    letterList = list(string)
    # For each word in the wordList, loop through each character in the word and check to see if the character is in our letter list, if it is increase matchCount by 1.
    matchList = []
    for word in wordList:
        matchCount = 0
        for char in word:
            if char in letterList:
                matchCount += 1
            # If matchCount is equal to the length of the word, all of the characters in the word are present in our letter list and the word should be added to our matchList.
            if matchCount == len(word):
                matchList.append(word)
    print(matchList)

getLetters()

输出:

Enter your target letters: xae
['axe']

答案 1 :(得分:0)

您的代码仅需进行简单的更改:

将wordList用作getLetters的参数。另外,如果您愿意,可以进行更改以了解单词的所有字母是否都在字母列表中。

def getLetters(wordList):
    string = input("Enter your target letters: ")
    letterList = list(string)
    matchList = []
    for word in wordList:
        if all([letter in letterList for letter in word]):
            matchList.append(word)
    return matchList

readWords中:

def readWords(filename):
    try:
        with open(filename) as file:
            s = file.read()
            wordList = s.split(" ")
            result = getLetters(wordList)
    except FileNotFoundError:
        print("...")
    else:
        # No exceptions.
        return result
相关问题