尝试使用文本文件而不是字符串变量

时间:2017-05-04 15:17:30

标签: python

我做过研究,但一直无法找到问题的解决方案。基本上我希望我的代码完成与现在完全相同的事情,但我希望能够用文本文件替换我的句子变量。这是我目前的代码:

from collections import OrderedDict
sentence= ("I met a traveller from an antique land, Who said Two vast and                 trunkless legs of stone. Stand 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 read Which 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 decay Of that colossal Wreck, boundless and bare The 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)

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)

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

choice = input ("do you want to uncompress or compress the text file (type   compress or uncompress)")
if choice == "compress":
    print (numberLst)
else:
    if choice == "uncompress":
        print (joinlst)

print("your choice was",choice)

2 个答案:

答案 0 :(得分:0)

with open("some_text_file.txt", "r") as text:
    for line in text:
        #do your thing

将它放在顶部并使用行替换代码中的句子。

答案 1 :(得分:0)

这会将filename处文件的全部内容读入变量sentence。请注意,sentence还会包含任何新行字符(或其他奇怪的编码垃圾),您可能需要使用split(...)和/或trim(...)调用过滤掉这些字符。

sentence = ""
with open(filename, 'r') as f:
    sentence = f.read()