我是Python新手,我正在尝试构建一个脚本,在其中导入包含正文的文本文件。我希望脚本阅读正文,并在一个名为(key_words)的列表中查找我定义的特定单词,该列表包含开头有大写字母(Nation)和小写字母(Nation)的单词。在Python完成搜索之后,它将在名为“单词列表”的新文本文件中垂直输出单词列表,以及单词在正文中出现的次数。如果我用文本体读取文本文件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()
这样你就可以在屏幕上看到结果了。
现在你必须把它保存在文件中。
更多文件使用
编辑:
使用此代码(my_script.py)
你可以运行脚本
然后得到
你可以用它来计算许多文件中的单词。
-
使用
readlines()
可以将所有行读入内存,因此需要更多内存-对于非常大的文件,这可能是个问题。在当前版本中
Counter()
计算所有行中的所有单词-测试它-但使用较少的内存。因此,使用
readlines()
可以得到相同的word_freq
,但是使用更多的内存。-
writelines(list_of_result)
不会在每一行后添加“\n”-也不会在“God:3”中添加“:”最好用类似的东西
编辑:新版本-将结果附加到单词列表的末尾。txt
编辑:将结果总和写入一个文件
相关问题 更多 >
编程相关推荐