Я новичок в Python и пытаюсь создать скрипт, в котором я импортирую text_file_1, содержащий текст. Я хочу, чтобы сценарий читал основной текст и искал определенные слова, которые я определил в списке под названием (key_words), который содержит слова с заглавной буквой в начале (Нация) и строчными буквами (нация). После того, как Python выполнит поиск, он выведет список слов по вертикали в новый текстовый файл под названием «Список слов» вместе с тем, сколько раз это слово встречается в теле. Если я прочитаю text_file_2 с текстом, он сделает то же самое, но ДОБАВИТ в список слов из исходного файла.
Пример:
Список слов
Файл 1:
God: 5
Nation: 4
creater: 8
USA: 3
Файл 2:
God: 10
Nation: 14
creater: 2
USA: 1
Вот что у меня есть до сих пор:
from sys import argv
from string import punctuation
script = argv[0] all_filenames = argv[1:]
print "Text file to import and read: " + all_filenames
print "\nReading file...\n"
text_file = open(all_filenames, 'r')
all_lines = text_file.readlines()
#print all_lines
text_file.close()
for all_filenames in argv[1:]:
print "I get: " + all_filenames
print "\nFile read finished!"
#print "\nYour file contains the following text information:"
#print "\n" + text_file.read()
#~ for word, count in word_freq.items():
#~ print word, count
keyWords = ['God', 'Nation', 'nation', 'USA', 'Creater', 'creater', 'Country', 'Almighty',
'country', 'People', 'people', 'Liberty', 'liberty', 'America', 'Independence',
'honor', 'brave', 'Freedom', 'freedom', 'Courage', 'courage', 'Proclamation',
'proclamation', 'United States', 'Emancipation', 'emancipation', 'Constitution',
'constitution', 'Government', 'Citizens', 'citizens']
for word in keyWords:
if word in word_freq:
output_file.write( "%s: %d\n" % (word, word_freq[word]) )
output_file = open("List_of_words.txt", "w")
for word in keyWords:
if word in word_freq:
output_file.write( "%s: %d\n" % (word, word_freq[word]) )
output_file.close()
Может быть, использовать этот код как-то?
import fileinput
for line in fileinput.input('List_of_words.txt', inplace = True):
if line.startswith('Existing file that was read'):
#if line starts Existing file that was read then do something here
print "Existing file that was read"
elif line.startswith('New file that was read'):
#if line starts with New file that was read then do something here
print "New file that was read"
else:
print line.strip()