I have a text file as :
sample.txt
JavaScript
x
3
1
Hi I am student
2
I am from
3
What I’ve tried is
JavaScript
1
13
13
1
import string
2
import re
3
4
def read_to_list1(filepath):
5
text_as_string = open(filepath, 'r').read()
6
x = re.sub('['+string.punctuation+']', '', text_as_string).split("n")
7
8
for i in x:
9
x_as_string = re.sub('['+string.punctuation+']', '', i).split()
10
print(x_as_string)
11
12
read_to_list1('sample.txt')
13
This results
JavaScript
1
3
1
['Hi,'I','am','student']
2
['I','am','from']
3
I want the result as:
JavaScript
1
2
1
[['Hi,'I','am','student'],['I','am','from']]
2
Advertisement
Answer
After opening the file, you can use a list comprehension to iterate over lines, and for each line str.split
on whitespace to get tokens for each sublist.
JavaScript
1
4
1
def read_to_list1(filepath):
2
with open(filepath, 'r') as f_in:
3
return [line.split() for line in f_in]
4