我有一个文本文件,我正在计算行数、字符数和单词数。如何通过使用 string.replace() 删除停用词(例如 (the, for, a))来清理数据
我现在有下面的代码。
前任。如果文本文件包含以下行:
"The only words to count are Apple and Grapes for this text"
Run Code Online (Sandbox Code Playgroud)
它应该输出:
2 Apple
2 Grapes
1 words
1 only
1 text
Run Code Online (Sandbox Code Playgroud)
并且不应该输出这样的词:
以下是我目前拥有的代码。
# Open the input file
fname = open('2013_honda_accord.txt', 'r').read()
# COUNT CHARACTERS
num_chars = len(fname)
# COUNT LINES
num_lines = fname.count('\n')
#COUNT WORDS
fname = fname.lower() # convert the text to lower first
words = fname.split()
d = {}
for w in words:
# if the word is repeated - start count
if w in d:
d[w] += 1
# if the word is only used once then give it a count of 1
else:
d[w] = 1
# Add the sum of all the repeated words
num_words = sum(d[w] for w in d)
lst = [(d[w], w) for w in d]
# sort the list of words in alpha for the same count
lst.sort()
# list word count from greatest to lowest (will also show the sort in reserve order Z-A)
lst.reverse()
# output the total number of characters
print('Your input file has characters = ' + str(num_chars))
# output the total number of lines
print('Your input file has num_lines = ' + str(num_lines))
# output the total number of words
print('Your input file has num_words = ' + str(num_words))
print('\n The 30 most frequent words are \n')
# print the number of words as a count from the text file with the sum of each word used within the text
i = 1
for count, word in lst[:10000]:
print('%2s. %4s %s' % (i, count, word))
i += 1
Run Code Online (Sandbox Code Playgroud)
谢谢
打开并读取文件 ( fname = open('2013_honda_accord.txt', 'r').read()) 后,您可以放置以下代码:
blacklist = ["the", "to", "are", "for", "this"] # Blacklist of words to be filtered out
for word in blacklist:
fname = fname.replace(word, "")
# The above causes multiple spaces in the text (e.g. ' Apple Grapes Apple')
while " " in fname:
fname = fname.replace(" ", " ") # Replace double spaces by one while double spaces are in text
Run Code Online (Sandbox Code Playgroud)
编辑: 为了避免包含不需要的单词的单词出现问题,您可以这样做(假设单词在句子中间):
blacklist = ["the", "to", "are", "for", "this"] # Blacklist of words to be filtered out
for word in blacklist:
fname = fname.replace(" " + word + " ", " ")
# Or .'!? ect.
Run Code Online (Sandbox Code Playgroud)
这里不需要检查双空格。
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
4208 次 |
| 最近记录: |