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

使用Python中的读取文本文件创建一个包含字符串的列表,python,python-3.x,Python,Python 3.x,我想用python制作一个混乱的游戏,它使用文本文件中的单词,而不是直接写入python文件中的单词(在本例中,代码可以完美地工作)。但当我想导入它们时,我会得到以下列表: [['amazement', ' awe', ' bombshell', ' curiosity', ' incredulity', '\r\n'], ['godsend', ' marvel', ' portent', ' prodigy', ' revelation', '\r\n'], ['stupefaction',

我想用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']]
我希望单词在一个列表中排序,例如:

["amazement", "awe", "bombshell"...]
这是我的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.")
我有一个文字文件:

    amazement, awe, bombshell, curiosity, incredulity,
    godsend, marvel, portent, prodigy, revelation,
    stupefaction, unforeseen, wonder, shock, rarity,
    miracle, abruptness, astonishment

谢谢你的帮助和建议

准一行程序是否:

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)
  • 在gen中为使用双精度
  • 根据空格进行拆分就是诀窍:它去掉了行终止字符和多个空格。然后,使用
    strip()
    去掉逗号即可
  • 对结果生成器应用排序后的
结果:

['abruptness', 'amazement', 'astonishment', 'awe', 'bombshell', 'curiosity', 'godsend', 'incredulity', 'marvel', 'miracle', 'portent', 'prodigy', 'rarity', 'revelation', 'shock', 'stupefaction', 'unforeseen', 'wonder']
这种快速方法的唯一缺点是,如果两个单词仅用逗号分隔,它将按原样发出这两个单词

在后一种情况下,只需像这样在gencomp中为
添加一个
,根据逗号执行拆分,并删除空结果字符串(
,如果word
):

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

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)
str.split()生成一个列表,因此如果将其附加到结果中,将得到一个列表列表。 一个解决方案是连接2个列表(+)

您可以通过在拆分“\r\n”之前先剥离i来删除它

使用

lst.extend(i)
而不是

lst.append(i)

split返回一个列表,您每次都会在列表中添加一个列表。改用extend将解决您的问题。

请尝试以下代码:

import random

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

name = "   My name   "

filename = "words/amazement_words.txt"

lst = []
file = open(filename, 'r')
data = file.readlines()

another_lst = []
for line in data:
    lst.append(line.strip().split(','))
print(lst)
for line in lst:
    for li in line:
        another_lst.append(li.strip())

print()
print()
print(another_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.")

一艘客轮成功了!谢谢你的详细回答和解释。@JureŠtabuc和Jean François Fabre♦, 有没有一种方法可以拆分“.”或“?”,这样以问号结尾的句子也可以拆分是的,使用正则表达式拆分,就像在我的另一个答案中一样:
import random

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

name = "   My name   "

filename = "words/amazement_words.txt"

lst = []
file = open(filename, 'r')
data = file.readlines()

another_lst = []
for line in data:
    lst.append(line.strip().split(','))
print(lst)
for line in lst:
    for li in line:
        another_lst.append(li.strip())

print()
print()
print(another_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.")