使用Python中的读取文本文件创建一个带有字符串的列表

Jur*_*buc 2 python python-3.x

我想用python做一个混乱的游戏,它使用文本文件中的单词,而不是直接写入python文件中的单词(在这种情况下,代码可以完美工作)。但是当我要导入它们时,我得到以下列表:

[['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction', ' unforeseen', ' wonder', ' shock', ' rarity', '\r\n'], ['miracle', ' abruptness', ' astonishment\r\n']]
Run Code Online (Sandbox Code Playgroud)

我希望单词在一个列表中排序,例如:

["amazement", "awe", "bombshell"...]
Run Code Online (Sandbox Code Playgroud)

这是我的python代码:

import random

#Welcome the player
print("""
    Welcome to Word Jumble.
        Unscramble the letters to make a word.
""")


filename = "words/amazement_words.txt"

lst = []
with open(filename) as afile:
    for i in afile:
        i=i.split(",")
        lst.append(i)
print(lst)

word = random.choice(lst)
theWord = word

jumble = ""
while(len(word)>0):
    position = random.randrange(len(word))
    jumble+=word[position]
    word=word[:position]+word[position+1:]
print("The jumble word is: {}".format(jumble))

#Getting player's guess
guess = input("Enter your guess: ")

#congratulate the player
if(guess==theWord):
    print("Congratulations! You guessed it")
else:
    print ("Sorry, wrong guess.")

input("Thanks for playing. Press the enter key to exit.")
Run Code Online (Sandbox Code Playgroud)

我有一个文字文件:

    amazement, awe, bombshell, curiosity, incredulity,
    godsend, marvel, portent, prodigy, revelation,
    stupefaction, unforeseen, wonder, shock, rarity,
    miracle, abruptness, astonishment
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助和任何建议!

Jea*_*bre 5

准一线可做到:

with open("list_of_words.txt") as f:
    the_list = sorted(word.strip(",") for line in f for word in line.split())

print(the_list)
Run Code Online (Sandbox Code Playgroud)
  • for在gen理解中使用double
  • 空格分割是诀窍:它消除了行终止字符和多个空格。然后,只需使用消除逗号strip()
  • 应用于sorted生成器理解

结果:

['abruptness', 'amazement', 'astonishment', 'awe', 'bombshell', 'curiosity', 'godsend', 'incredulity', 'marvel', 'miracle', 'portent', 'prodigy', 'rarity', 'revelation', 'shock', 'stupefaction', 'unforeseen', 'wonder']
Run Code Online (Sandbox Code Playgroud)

这种快速方法的唯一缺点是,如果2个单词仅用逗号分隔,它将按原样发布2个单词。

在后一种情况下,只需for在gencomp中添加一个这样的内容即可根据逗号进行拆分,然后删除空的结果字符串(if word):

with open("list_of_words.txt") as f:
    the_list = sorted(word for line in f for word_commas in line.split() for word in word_commas.split(",") if word)

print(the_list)
Run Code Online (Sandbox Code Playgroud)

或者在后一种情况下,也许使用正则表达式拆分会更好(我们也需要丢弃空字符串)。拆分表达式为空白或逗号。

import re

with open("list_of_words.txt") as f:
    the_list = sorted(word for line in f for word in re.split(r"\s+|,",line) if word)
Run Code Online (Sandbox Code Playgroud)