Python 如何打印由数字列表指定的文件行?
我打开一本字典,拉特定的行,这些行将使用列表指定,最后我需要在一行中打印一个完整的句子 我想打开一本每行都有一个单词的词典 然后在一行中打印一个句子,单词之间留有空格:Python 如何打印由数字列表指定的文件行?,python,list,readfile,lines,Python,List,Readfile,Lines,我打开一本字典,拉特定的行,这些行将使用列表指定,最后我需要在一行中打印一个完整的句子 我想打开一本每行都有一个单词的词典 然后在一行中打印一个句子,单词之间留有空格: N = ['19','85','45','14'] file = open("DICTIONARY", "r") my_sentence = #????????? print my_sentence 如果您的词典不是太大(即可以容纳您的内存): 编辑:一个小的澄清,原来的帖子没有使用空格来加入单词,我已经修改了代码来包含它
N = ['19','85','45','14']
file = open("DICTIONARY", "r")
my_sentence = #?????????
print my_sentence
如果您的
词典不是太大(即可以容纳您的内存):
编辑:一个小的澄清,原来的帖子没有使用空格来加入单词,我已经修改了代码来包含它。如果需要用逗号或其他可能需要的分隔符分隔单词,也可以使用“,”。join(…)
。另外,请记住,此代码使用从零开始的行索引,因此词典的第一行是0,第二行是1,以此类推
更新::如果您的字典太大,无法存储,或者您只想消耗尽可能少的内存(如果是这样,为什么您首先要使用Python?;),那么您只能“提取”您感兴趣的单词:
N = [19, 85, 45, 14]
words = {}
word_indexes = set(N)
counter = 0
with open("DICTIONARY", "r") as f:
for line in f:
if counter in word_indexes:
words[counter] = line.strip()
counter += 1
my_sentence = " ".join([words[i] for i in N])
您可以使用linecache.getline
获取所需的特定行号:
import linecache
sentence = []
for line_number in N:
word = linecache.getline('DICTIONARY',line_number)
sentence.append(word.strip('\n'))
sentence = " ".join(sentence)
这里有一个简单的方法,有更基本的方法:
n = ['2','4','7','11']
file = open("DICTIONARY")
counter = 1 # 1 if you're gonna count lines in DICTIONARY
# from 1, else 0 is used
output = ""
for line in file:
line = line.rstrip() # rstrip() method to delete \n character,
# if not used, print ends with every
# word from a new line
if str(counter) in n:
output += line + " "
counter += 1
print output[:-1] # slicing is used for a white space deletion
# after last word in string (optional)
我需要将第19行、第85行、第45行和第14行拉出来,然后将它们打印在一行中。我的N列表是字符串,我无法编辑它。。所以现在它给了我以下信息,我的句子=”.join([words[i]表示我在wordNumbers中的i])TypeError:string索引必须是整数,而不是stri。我正在从一个文件中提取列表,使用以下命令打开(“我的随机列表”,“r”)作为文件:data=file.read()N=data.rstrip().split(“\N”)为什么不能编辑它?如果需要,您可以从中创建一个临时整数列表:N\u fixed=[int(i)for i in N]
并使用该列表。如果您没有使用第二个“内存感知”代码,只需使用words[int(i)]
而不是words[i]
。@user7451333-您可以使用以下命令将文件直接加载到int
列表中:N=[int(i)for i in data.rstrip().split(“\N”)]
n = ['2','4','7','11']
file = open("DICTIONARY")
counter = 1 # 1 if you're gonna count lines in DICTIONARY
# from 1, else 0 is used
output = ""
for line in file:
line = line.rstrip() # rstrip() method to delete \n character,
# if not used, print ends with every
# word from a new line
if str(counter) in n:
output += line + " "
counter += 1
print output[:-1] # slicing is used for a white space deletion
# after last word in string (optional)