简体   繁体   中英

how can I print lines of a file that specefied by a list of numbers Python?

I open a dictionary and pull specific lines the lines will be specified using a list and at the end i need to print a complete sentence in one line.

I want to open a dictionary that has a word in each line then print a sentence in one line with a space between the words:

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

print my_sentence

If your DICTIONARY is not too big (ie can fit your memory):

N = [19,85,45,14]

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

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

EDIT: A small clarification, the original post didn't use space to join the words, I've changed the code to include it. You can also use ",".join(...) if you need to separate the words by a comma, or any other separator you might need. Also, keep in mind that this code uses zero-based line index so the first line of your DICTIONARY would be 0, the second would be 1, etc.

UPDATE: : If your dictionary is too big for your memory, or you just want to consume as little memory as possible (if that's the case, why would you go for Python in the first place? ;)) you can only 'extract' the words you're interested in:

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

you can use linecache.getline to get specific line numbers you want:

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

Here's a simple one with more basic approach:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM