So I have a really long string from a text document made entirely up of 7-letter words. I need to separate them and store each 7-letter word into an list.
The text document is originally made up of 7-letter words each separated by lines. A small part of it is shown below: Screenshot of the text document
After the space is removed it looks like this: Screenshot of string with lines removed A solution of how to store them in a list straight from the form of being separated in lines would also work for me.
I used this to remove the new lines:
with open(r"C:\Users\HP\Desktop\input.txt", 'r') as file:
data = file.read().replace('\n', '')
print(data)
Thanks.
CodePudding user response:
Use the split function, which creates a list of tokens based on the provided delimiter. You can provide a '\n' delimiter, something like this:
with open('input.txt', 'r') as file:
data = file.read()
separated_list = data.split('\n')
print(separated_list)
output:
['abc', 'def', 'hij']
CodePudding user response:
The above answeris right, but I like to use readlines() with a list comprehension
with open('words.txt') as file:
data = [word.replace('\n','') for word in file.readlines()]
CodePudding user response:
You can replace a new line with a space and then split the whole text to get a list of words
data = file.read().replace('\n', ' ').split()