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

时间:2016-11-06 11:04:45

标签: 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']]

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

["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

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

4 个答案:

答案 0 :(得分:4)

准单行做到了:

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-comprehension中使用双for
  • 分裂空格是一个诀窍:它摆脱了行终止字符和多个空格。然后,使用strip()删除逗号。
  • 在生成的生成器理解
  • 上应用sorted

结果:

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

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

在后一种情况下,只需在gencomp中添加for,以便根据逗号执行拆分并删除空结果字符串(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)

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

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)

答案 1 :(得分:1)

请尝试以下代码:

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.")

答案 2 :(得分:0)

str.split()会生成一个列表,因此如果将其附加到结果中,则会获得一个列表列表。 解决方案是连接2列表(+)

你可以摆脱' \ r \ n'在拆分之前剥离我

答案 3 :(得分:0)

使用

lst.extend(i)

而不是

lst.append(i)

split返回一个列表,每次都会列出一个列表。使用extend代替将解决您的问题。