【问题标题】:How to print words that only cointain letters from a list?如何打印仅包含列表中字母的单词?
【发布时间】:2016-09-17 16:34:59
【问题描述】:

你好我最近一直在尝试在 Python 3 中创建一个程序,它将读取一个包含 23005 个单词的文本文件,然后用户将输入一个 9 个字符的字符串,程序将使用它来创建单词并将它们与文本文件中的单词进行比较。

我想打印包含 4-9 个字母并且还包含列表中间的字母的单词。例如,如果用户输入字符串“anitsksem”,那么第五个字母“​​s”必须出现在单词中。

这是我自己已经走了多远:

# Open selected file & read
filen = open("svenskaOrdUTF-8.txt", "r")

# Read all rows and store them in a list
wordList = filen.readlines()

# Close File
filen.close()

# letterList index
i = 0
# List of letters that user will input
letterList = []
# List of words that are our correct answers
solvedList = []

# User inputs 9 letters that will be stored in our letterList
string = input(str("Ange Nio Bokstäver: "))
userInput = False

# Checks if user input is correct
while userInput == False:
   # if the string is equal to 9 letters
   # insert letter into our letterList.
   # also set userInput to True
    if len(string) == 9:
        userInput = True
        for char in string:
            letterList.insert(i, char)
            i += 1

    # If string not equal to 9 ask user for a new input
    elif len(string) != 9:
        print("Du har inte angivit nio bokstäver")
        string = input(str("Ange Nio Bokstäver: "))

# For each word in wordList
# and for each char within that word
# check if said word contains a letter from our letterList
# if it does and meets the requirements to be a correct answer
# add said word to our solvedList

for word in wordList:
    for char in word:
        if char in letterList:
            if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
                print("Char:", word)
                solvedList.append(word)

我遇到的问题是,它不是打印包含来自我的letterList 的字母的单词,而是打印出包含至少一个来自我的字母的单词我的letterList。这也意味着某些单词会被多次打印出来,例如,如果单词包含来自letterList 的多个字母。

我一直在尝试解决这些问题,但我似乎无法弄清楚。我还尝试使用排列来创建列表中所有可能的字母组合,然后将它们与我的wordlist 进行比较,但是我认为鉴于必须创建的组合数量,解决方案会变慢。

    # For each word in wordList
    # and for each char within that word
    # check if said word contains a letter from our letterList
    # if it does and meets the requirements to be a correct answer
    # add said word to our solvedList
    for word in wordList:
        for char in word:
            if char in letterList:
                if len(word) >= 4 and len(word) <= 9 and letterList[4] in word:
                    print("Char:", word)
                    solvedList.append(word)

另外,由于我对 python 有点陌生,如果您有任何一般性提示要分享,我将不胜感激。

【问题讨论】:

    标签: python python-3.x for-loop comparison iteration


    【解决方案1】:

    您得到多个单词主要是因为您遍历给定单词中的每个字符,如果该字符在 letterList 中,则附加并打印它。

    相反,基于单词而不是基于字符进行迭代,同时还使用with 上下文管理器自动关闭文件:

    with open('american-english') as f:
        for w in f:
            w = w.strip()
            cond = all(i in letterList for i in w) and letterList[4] in w
            if 9 > len(w) >= 4 and cond:
                print(w)
    

    这里cond用于修剪if语句,all(..)用于检查单词中的每个字符是否在letterList中,w.strip()用于删除任何多余的空格。

    此外,要在输入为 9 字母时填充您的 letterList不要使用 insert。相反,只需将字符串提供给list,列表将以类似但明显更快的方式创建:

    这个:

    if len(string) == 9:
        userInput = True
        for char in string:
            letterList.insert(i, char)
            i += 1
    

    可以写成:

    if len(string) == 9:
        userInput = True
        letterList = list(string)
    

    通过这些更改,不需要初始的openreadlines,也不需要初始化letterList

    【讨论】:

    • 哇,谢谢你,这样代码看起来更干净了,但是我仍然遇到了一个问题。当程序打印出结果时,它会打印出不包含 letterList 中字母的单词。例如,如果我使用字符串“anitsksem”,我会得到包含不在 letterList 中的字母(如 b、d、u 等)的单词。我如何确保单词仅包含来自 letterList 的字母
    • 对,我错过了。查看更新版本,看看它是否符合您的要求@PeterYakob。
    • 谢谢它就像一个魅力。如果您有时间,请跟进问题,如果我只想打印出在 letterList once 中使用单个字母的单词,例如如果 letterList = ["a", "n", "i", "b", "s", "l", "s", "y", "m"] 程序不会打印出类似的单词:' animal',因为字母 'a' 在我们的列表中只出现一次,但是如果我们在上面的 letterList 示例中多次出现像 's' 这样的字母,我们可以打印出:'abyss'
    【解决方案2】:

    你可以试试这个逻辑:

    for word in wordList:
        # if not a valid work skip - moving this check out side the inner for-each will improve performance
        if len(word) < 4 or len(word) > 9 or letterList[4] not in word:
            continue
        # find the number of matching words
        match_count = 0
        for char in word:
            if char in letterList:
                match_count += 1
        # check if total number of match is equal to the word count
        if match_count == len(word):
            print("Char:", word)
            solvedList.append(word)
    

    【讨论】:

      【解决方案3】:

      您可以使用 lambda 函数来完成这项工作。 我只是在这里建立一个 POC,让您将其转换为完整的解决方案。

      filen = open("test.text", "r")
      word_list = filen.read().split()
      print("Enter your string")
      search_letter = raw_input()[4]
      
      solved_list  = [ word for word in word_list if  len(word) >= 4 and len(word) <= 9 and search_letter in word]
      print solved_list
      

      【讨论】:

      • 我的答案是 Python27,所以我不得不使用 raw_input 而不是 input。
      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      • 2015-07-30
      相关资源
      最近更新 更多