如何打印由数字列表指定的文件行?

2024-03-29 00:18:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我打开一本字典,拉特定的行行行将指定使用一个列表,在最后我需要打印一个完整的句子在一行。你知道吗

我想打开一本每行都有一个单词的词典 然后在一行中打印一个句子,单词之间留有空格:

N = ['19','85','45','14']
file = open("DICTIONARY", "r") 
my_sentence = #?????????

print my_sentence

Tags: 列表dictionary字典myopen单词sentence句子
3条回答

如果您的DICTIONARY不是太大(即可以容纳您的内存):

N = [19,85,45,14]

with open("DICTIONARY", "r") as f:
    words = f.readlines()

my_sentence = " ".join([words[i].strip() for i in N])

编辑:一个小的澄清,原来的帖子没有用空格来连接单词,我已经修改了代码来包含它。如果需要用逗号或任何其他可能需要的分隔符分隔单词,也可以使用",".join(...)。另外,请记住,此代码使用基于零的行索引,因此DICTIONARY的第一行是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)

相关问题 更多 >