简体   繁体   中英

read words from file, line by line and concatenate to paragraph

I have a really long list of words that are on each line. How do I make a program that takes in all that and print them all side by side?

I tried making the word an element of a list, but I don't know how to proceed.

Here's the code I've tried so far:

def convert(lst):
    return([i for item in lst for i in item.split()])

lst = [''' -The list of words come here- ''']

print(convert(lst))

If you already have the words in a list, you can use the join() function to concatenate them. See https://docs.python.org/3/library/stdtypes.html#str.join

words = open('your_file.txt').readlines()
separator = ' '
print(separator.join(words))

Another, a little bit more cumbersome method would be to print the words using the builtin print() function but suppress the newline that print() normally adds automatically to the end of your argument.

words = open('your_file.txt').readlines()
for word in words:
  print(word, end=' ')

Try this, and example.txt just has a list of words going down line by line.

with open("example.txt", "r") as a_file:
    sentence = ""
    for line in a_file:
        stripped_line = line.strip()
        sentence = sentence + f"{stripped_line} "
print(sentence)

If your input file is really large and you cant fit it all in memory, you can read the words lazy and write them to disk instead of holding the whole output in memory.

# create a generator that yields each individual line
lines = (l for l in open('words'))

with open("output", "w+") as writer:
  # read the file line by line to avoid memory issues
  while True:
    try:
      line = next(lines)
      # add to the paragraph in the out file
      writer.write(line.replace('\n', ' '))
    except StopIteration:
      break

You can check the working example here: https://replit.com/@bluebrown/readwritewords#main.py

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