我试图把我的程序的输出全部放在一行上,当我打印"end=''“时,它似乎不起作用。有什么想法吗?
这是我的代码:
import random
thesaurus = {}
with open('thesaurus.txt') as input_file:
for line in input_file:
synonyms = line.split(',')
thesaurus[synonyms[0]] = synonyms[1:]
print ("Total words in thesaurus: ", len(thesaurus))
# input
phrase = input("Enter a phrase: ")
# turn input into list
part1 = phrase.split()
part2 = list(part1)
newlist = []
for x in part2:
s = random.choice(thesaurus[x]) if x in thesaurus else x
s = random.choice(thesaurus[x]).upper() if x in thesaurus else x
newlist.append(s)
newphrase = ' '.join(newlist)
print(newphrase, end=' ')现在,出于某种原因,我的程序正在打印出来:
i LOVE FREEDOM
SUFFICIENCY apples输入“我喜欢吃苹果”
预期产出是:
i LOVE FREEDOM SUFFICIENCY apples任何帮助都将不胜感激!
发布于 2016-05-10 02:25:51
这与end=''一点问题都没有。从文件中读取的行仍然有换行符。拆分行时,最后一个条目将有一个换行符,如下例所示:
>>> 'foo,bar,baz\n'.split(',')
['foo', 'bar', 'baz\n']你的问题是你取代了"FREEDOM\n"而不仅仅是"FREEDOM"。在使用前,只需去掉这一行:
thesaurus = {}
with open('thesaurus.txt') as input_file:
for line in input_file:
synonyms = line.strip().split(',')
thesaurus[synonyms[0]] = synonyms[1:]https://stackoverflow.com/questions/37127944
复制相似问题