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])
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)
如果您的
DICTIONARY
不是太大(即可以容纳您的内存):编辑:一个小的澄清,原来的帖子没有用空格来连接单词,我已经修改了代码来包含它。如果需要用逗号或任何其他可能需要的分隔符分隔单词,也可以使用
",".join(...)
。另外,请记住,此代码使用基于零的行索引,因此DICTIONARY
的第一行是0,第二行是1,依此类推更新::如果你的字典对于你的内存来说太大了,或者你只是想消耗尽可能少的内存(如果是这样的话,你为什么首先选择Python呢?;))您只能“提取”您感兴趣的单词:
可以使用
linecache.getline
获取所需的特定行号:这里有一个简单的方法,有更基本的方法:
相关问题 更多 >
编程相关推荐