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()
words = 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()
您好,我在我的代码中创建的单词文件有问题,当我连接列表中的所有单词时,它会写入文件中,如下所示:imetatravellerfromanantiqueland,whosaid-“twovastandtrunklesslegsofstonestandinthedesert。 ... nearthem,onthesand,halfsunkashatteredvisagelies,whosefrown,andwrinkledlip,andsneerofcoldcommand,tellthatitssculptorwellthosepassionsreadwhichyetsurvive,stampedontheselifelessthings,thehandthatmockedthem,andtheheartthatfed; andonthepedestal,thesewordsappear:!mynameisozymandias,kingofkings; lookonmyworks,yemighty,anddespair nothingbesideremains.roundthedecayofthatcolossalwreck,boundlessandbaretheloneandlevelsandsstretchfaraway
问题是文件中写入的单词之间没有空格,因此很难识别文件中的单词。一旦修好,它最好是这样的:(我:遇见:a:旅行者:来自:a:古董:土地)(仅作为例子)
如果你能得到帮助,我将不胜感激,谢谢。
答案 0 :(得分:0)
问题是,当你加入开头的单词时,你会使用''。您应该从以下位置更改该行:
words_str = ''.join(words)
为:
words_str = ' '.join(words) # Separates the words with spaces
如果您希望它以常规空格分隔,或
words_str = ':'.join(words) # Separates the words with ':'
如果您希望将其分隔为':'