2017-02-20 57 views
0
from collections import OrderedDict 
sentence= ("I met a traveller from an antique land,Who said—“Two vast and trunkless legs of stoneStand in the desert. . . . Near them, on the sand,Half sunk a shattered visage lies, whose frown,And wrinkled lip, and sneer of cold command,Tell that its sculptor well those passions readWhich yet survive, stamped on these lifeless things,The hand that mocked them, and the heart that fed;And on the pedestal, these words appear:My name is Ozymandias, King of Kings;Look on my Works, ye Mighty, and despair!Nothing beside remains. Round the decayOf that colossal Wreck, boundless and bareThe lone and level sands stretch far away.").lower() 

字= sentence.split(”“)创建从一个列表中的文件用空格

lst = list(OrderedDict.fromkeys(words)) 
numberLst = [] 
for i in words: 
    numberLst.append(lst.index(i)+1) 

print(lst) 
print (numberLst) 

words_str = ''.join(words) 
numberLst_str = ''.join(str(e) for e in numberLst) 

file = open("words.txt","w") 
file.write(words_str) 
file.close() 

file=open("numberlst.txt","w") 
file.write(numberLst_str) 
file.close() 

joinlst = " ".join(lst[i-1] for i in numberLst) 

print (joinlst) 

file=open("joinlst.txt","w") 
file.write(joinlst) 
file.close() 

您好,我有一个问题,我的话的文件,我在我的代码已经创建,它是当我连接我列表中的所有单词时,它会被写入文件中:imetatravellerfromananlandland,whosaid-“两个无边无角的石块,搁置在插入的......黑暗,背景,半暗视野,视角,告诉它, andonthepedestal,thesewordsappear:mynameisozymandia S,kingofkings;!lookonmyworks,yemighty,anddespair nothingbesideremains.roundthedecayofthatcolossalwreck,boundlessandbaretheloneandlevelsandsstretchfaraway。

问题是在文件中写入的单词之间没有空格,因此很难识别文件中的单词。一旦修好它最好看起来像这样:(我:遇见:a:旅客:从:an:古董:土地)(仅作为例子)

如果你能请帮助它将不胜感激,谢谢。

+0

我不是在追随你想要的?你想只写出用':'分开的单词吗? –

+0

您好像在'''.join(words)'中加入了一个空字符串的单词。在那里添加冒号,所以'':'。join(words)'。但是,你稍后在'joinlst =“”.join(lst [i-1]为我在numberLst中)正确地使用一个空格'',所以我不确定我是否理解。 – roganjosh

回答

0

问题是,当您在开始时加入单词时,请使用''。您应该改变该行从:

words_str = ''.join(words) 

到:

words_str = ' '.join(words) # Separates the words with spaces 

如果你想要通过常规空格隔开,或

words_str = ':'.join(words) # Separates the words with ':' 

如果你想要通过分离 ':'