当我尝试从文件中读取时,我遇到了一个恼人的错误,我认为它与变量的列表格式有关,但我不确定。
如果有人可以帮助解决这个问题,那就太棒了。 我认为这也与列表末尾的打印有关。
这是我的代码:
def one():
print ("")
print ("You have chosen to read the file!")
print ("")
file = open("sentence.txt" , "r")
words = file.readlines(1)
nums = file.readlines(2)
#Remove "\n"
#This bit doesn't work, I'm not sure how to remove "\n"
#These were me trying to get rid of the "\n"
#map(str.strip, words)
#words = words.strip('\n')
print(words)
print (nums)
print ("")
#Reconstruct sentence here
答案 0 :(得分:1)
函数file.readlines()
不接受行数的参数,它一次读取文件的所有行。 (对于记录,如果你确实传递了像file.readlines(n)
这样的参数,则参数n
是一个"提示"关于要读取的字节数...更多信息请点击{ {3}})
def one():
print ("")
print ("You have chosen to read the file!")
print ("")
file = open("sentence.txt" , "r")
lines = file.readlines() # read all the lines into a list
words = lines[0]
nums = lines[1]
#Remove "\n"
#This bit doesn't work, I'm not sure how to remove "\n"
#These were me trying to get rid of the "\n"
#map(str.strip, words)
words = words.strip("\n][").replace("'", "").split(",")
nums = nums.strip("\n][").replace("'", "").split(",")
nums = list(map(int, numbers)) ## assuming you want to convert the string to integers, use this
print(words)
print (nums)
print ("")
#Reconstruct sentence here
remade_sentence = ' '.join([words[i-1] for i in nums]) ## changed empty string to space to add spaces
print (remade_sentence)
file.close() ## also, make sure to close your file!
编辑:我已更新代码以处理nums
作为字符串列表
编辑2:更新代码以反映@ notevenwrong删除括号和引号的方法
编辑3:重新简化...当我在文本编辑器中打开输入文件时,我真的看到了:
['the', 'dog', 'cat']
[1, 1, 1, 2, 1, 3]
如果这不是正确的输入,则此代码可能无效。
答案 1 :(得分:1)
file.readlines(1)
返回的是单个元素列表,元素是字符串。您想要做的是获取字符串本身并替换' \ n',' [',']'等。
尝试
words[0].strip("\n][").replace("'", "").split(",")
答案 2 :(得分:0)
你在[单词[i-1]中得到例外,因为我是str,你可以表演 - :' str'和' int'。
>>> i = '1'
>>> i -1
Traceback (most recent call last):
File "<pyshell#101>", line 1, in <module>
i -1
TypeError: unsupported operand type(s) for -: 'str' and 'int'
快速修复应该是 -
remade_sentence = ''.join([words[int(i)-1] for i in nums])