There are two sentnecs in “test.txt”
sentence1 = A sentence is a grammatical unit consisting of one or more words.
sentence2 = A sentence can also be defined in orthographic terms alone.
count_line = 0
for line in open('C:/Users/Desktop/test.txt'):
count_line = count_line +1
fields = line.rstrip('\n').split('\t')
##print count_line, fields
file = open('C:/Users/Desktop/test_words.txt', 'w+')
count_word = 0
for words in fields:
wordsplit = words.split()
for word in wordsplit:
count_word = count_word + 1
print count_word, word
file.write(str(count_word) + " " + word + '\n')
file.close()
My result in “test_words.txt” showed only the words from second sentence:
1 A
2 sentence
3 can
4 also
5 be
6 defined
7 in
8 orthographic
9 terms
10 alone.
How to also write the words from the first sentence in and follow by the words in second sentence “test_words.txt” ?
Any suggestion?
The reason this is happening is because when you open the file for the second time, you dont preserve the original text inside it. When you open a file and write to it in Python, you basically overwrite its contents unless you store them in a variable and re-write them.
Try this code:
Here’s the output when i run it:
Here’s code without
enumerate():