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

3
我打算打开一个字典,使用列表指定特定的行,最后需要在一行上打印出完整的句子。我想打开一个字典,每一行都有一个单词,然后在这些单词之间用空格打印成一个完整的句子。
N = ['19','85','45','14']
file = open("DICTIONARY", "r") 
my_sentence = #?????????

print my_sentence

1
我需要提取第19行、85行、45行和14行,然后将它们打印在同一行上。 - user7451333
3个回答

2
如果你的 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
我的 N 列表是字符串类型,我无法编辑它。因此,现在它给了我以下错误提示:my_sentence = "".join([words[i] for i in wordNumbers]) TypeError: 字符串索引必须是整数,而不是字符串。 - user7451333
1
我正在使用以下代码从文件中拉取列表:with open("my_random_list", "r") as file: data = file.read()N = data.rstrip().split("\n") - user7451333
1
为什么不能编辑它?如果需要,您可以从中创建一个临时整数列表:N_fixed = [int(i) for i in N],并使用该列表。如果您没有使用第二个“内存感知”的代码,请改用words[int(i)]而不是words[i]... - zwer
1
@user7451333 - 你可以使用以下代码将文件直接加载到一个 int 列表中:N = [int(i) for i in data.rstrip().split("\n")] - zwer

2
您可以使用 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

这是一个更基础的简单示例:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接