[英]How can I read a file into a list of tuples including the line number?
I want to read a file into a list of tuples that stores the word itself and the line it is on.我想将文件读入存储单词本身及其所在行的元组列表中。
listinput = []
with open(args.infile, "r") as filein:
for line in filein:
line = line.strip(" .,!?\n\t")
line = line.lower()
tuples = line.split()
listinput.append(tuples)
print(listinput)
I also don't know how to get the line number in it.我也不知道如何获取其中的行号。 I am also not sure if i created a list of tuples right.
我也不确定我是否正确创建了元组列表。
the content of the file, as well as the current and expected output, is not specified so I'm not sure what the content looks like, but:未指定文件的内容以及当前和预期的输出,因此我不确定内容是什么样的,但是:
you can use enumerate
to also get the line number as you iterate lines您可以在迭代行时使用
enumerate
来获取行号
does this work for you?这对你有用吗?
listinput = []
with open(args.infile, "r") as filein:
for num, line in enumerate(filein):
line = line.strip(" .,!?\n\t")
line = line.lower()
tuples = (num, *line.split())
listinput.append(tuples)
print(listinput)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.