使用python的字计数器 [英] Word counter using python
问题描述
我用python写了一个字数统计代码.
I wrote a code for word count in python.
我想从以下页面获取每个单词的文本和频率:http://www.holybible.or.kr/B_NIV/cgi/bibleftxt.php?VR=NIV&VL=1&CN=1&CV=99
I wanted to get text and frequency of each words from the following page: http://www.holybible.or.kr/B_NIV/cgi/bibleftxt.php?VR=NIV&VL=1&CN=1&CV=99
问题是我的程序给了我除以每节经文的字数,但我希望它不分开.
Problem is that my program is giving me the word count divided by each verses, but I want it undivided.
请帮我解决这个问题.
import requests
from bs4 import BeautifulSoup
import operator
def start(url):
word_list = []
source_code = requests.get(url).text
soup = BeautifulSoup(source_code, "html.parser")
for bible_text in soup.findAll('font', {'class': 'tk4l'}):
content = bible_text.get_text()
words = content.lower().split()
for each_word in words:
word_list.append(each_word)
clean_up_list(word_list)
def clean_up_list(word_list):
clean_word_list = []
for word in word_list:
symbols = "~!@#$%^&*()_+`{}|\"?><`-=\][';/.,']"
for i in range(0, len(symbols)):
word = word.replace(symbols[i], "")
if len(word) > 0:
clean_word_list.append(word)
create_dictionary(clean_word_list)
def create_dictionary(clean_word_list):
word_count = {}
for word in clean_word_list:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
for key, value in sorted(word_count.items(),key=operator.itemgetter(0)):
print(key, value)
start('http://www.holybible.or.kr/B_NIV/cgi/bibleftxt.php?VR=NIV&VL=1&CN=1&CV=99')
<小时>
推荐答案
您正在为每节经文构建一个新的 word_count
字典,然后打印出 word_count
仅用于这节经文.相反,您只需要一个 word_count
实例.
You are building a fresh word_count
dictionary for every verse and then you printing out the word_count
for only this verse. Instead you need to have only one instance of word_count
.
更新:代码存在其他问题,此外您应该使用正则表达式删除所有非字母数字字符,此外您应该使用 collections.Counter
,如它使您的代码更短,并且作为一个很好的副作用,让您检索最常用的单词:
Update: There were other problems with the code, plus you should use regular expressions to remove all non-alphanumeric characters, plus you should use collections.Counter
, as it makes your code a lot shorter, and, as a nice side effect, let's you retrieve the most common words:
import requests
import re
from bs4 import BeautifulSoup
from collections import Counter
def parse(url):
html = requests.get(url).text
soup = BeautifulSoup(html, "html.parser")
count = Counter()
for bible_text in soup.findAll('font', {'class': 'tk4l'}):
text = re.sub("[^\w0-9 ]", "", bible_text.get_text().lower())
count.update(text.split(" "))
return count
word_count = parse('http://www.holybible.or.kr/B_NIV/cgi/bibleftxt.php?VR=NIV&VL=1&CN=1&CV=99')
print(word_count.most_common(10))
输出:
[('the', 83), ('and', 71), ('god', 30), ('was', 29), ('to', 22), ('it', 17), ('of', 16), ('there', 16), ('that', 15), ('in', 15)]
这篇关于使用python的字计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!