简体   繁体   English

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

[英]Printing only words from a list that contain characters from another list?

I am working on a small problem for fun, sent to me by a friend. 我正在为一个小小的问题寻找乐趣,由朋友送给我。 The problem requires me to populate an array with common words from a text file, and then print all the words from this list containing certain characters provided by the user. 问题要求我使用文本文件中的常用单词填充数组,然后打印此列表中包含用户提供的某些字符的所有单词。 I am able to populate my array no problem, but it seems the part of the code that actually compares the two lists is not working. 我能够填充我的数组没有问题,但似乎实际比较两个列表的代码部分是行不通的。 Below is the function I've written to compare the 2 lists. 下面是我为比较2个列表而编写的函数。

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

The code runs just fine, I don't get any error output, but once the user enters their list of letters, nothing happens. 代码运行得很好,我没有得到任何错误输出,但一旦用户输入他们的字母列表,没有任何反应。 To test I've tried a few inputs matching up with words I know are in my wordList (eg added, axe, tree, etc). 为了测试我已经尝试了一些与我知道的单词匹配的输入在我的wordList中(例如添加,ax,树等)。 But nothing ever prints after I enter my letter string. 但是在输入我的字母串之后什么都没打印。

This is how I populate my 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()

Edit: Changed the function to reset matchCount to 0 before it starts looping characters, still no output. 编辑:更改函数以在开始循环字符之前将matchCount重置为0,仍然没有输出。

Edit: add a global declaration to modify your list from inside a function: 编辑:添加一个全局声明来修改函数内的列表:

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

Here is a working example: 这是一个工作示例:

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

output: 输出:

Enter your target letters: xae
['axe']

Your code only needs a simple change: 您的代码只需要一个简单的更改:

Pass wordList as a parameter for getLetters . 将wordList作为getLetters的参数getLetters Also if you like you could make a change in order to know if all the letters of the word are in the letter list. 此外,如果您愿意,可以进行更改,以便知道单词的所有字母是否都在字母列表中。

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

And in readWords : 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从一个列表中排除包含另一个列表中的一个或多个字符的单词 python - Exclude words from a list that contain one or more characters from another list python 打印字典中的单词列表 - Printing list of words from dictionary 只从包含某些字符的列表中打印出字符串 - Only print out strings from a list that contain certain characters 从列表中打印单词到pygame中的特定坐标 - Printing words from a list, to specific coordinates in pygame 如果其中的一个单词在Python中不包含某些字符,如何从列表列表中删除一行? - How to remove a row from a list of lists if one of the words in it does not contain certain characters in Python? 从字符串中获取不在另一个列表中的单词列表 - Get a list of words from a string that are not in another list 将字符从 dict 映射到单词列表 - mapping characters from dict to a list of words 从包含某些字符的列表中删除单词 - Remove words from list containing certain characters 如何使用Python从单词列表中删除不需要的字符并将其清除到另一个列表中? - How can I remove unwanted characters from a words list and put them cleared in another list using Python? 如何从包含另一个列表中的所有特定字符的列表中获取项目 - How to get items from a list that contain all specific characters from another one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM