如何打印由Python数字列表拼写的文件行?

时间:2017-02-19 16:53:10

标签: python list readfile lines

我打开一个字典并拉出特定的行,使用列表指定行,最后我需要在一行中打印完整的句子。

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

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

print my_sentence

3 个答案:

答案 0 :(得分:1)

如果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])

答案 1 :(得分:1)

您可以使用linecache.getline获取所需的特定行号:

import linecache
sentence = []
for line_number in N:
    word = linecache.getline('DICTIONARY',line_number)
    sentence.append(word.strip('\n'))
sentence = " ".join(sentence)

答案 2 :(得分:1)

这是一个简单的基本方法:

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)