selfteaching / selfteaching/selfteaching-python-camp
Day06 字频统计作业的问题
Open
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 151
- Forks
- 875
- PR merge metrics
- No merged PRs in 30d
Description
方法一:
def stats_text_en(text):
"""count english words in the text"""
result=text.replace(',',' ').replace('.','').replace('!','').replace('*',' ').replace('-','').replace('?','')
result1=result.split()
wordcount={}
for i in result1:
wordcount=result1.count(i)
wordcount=sorted(wordcount.items(),key=lambda x:x[1],reverse=True)
return wordcount
#执行函数
text='''
python is interesting and learning is interesting too.'''
print(stats_text_en(text))
结果显示:
wordcount=sorted(wordcount.items(),key=lambda x:x[1],reverse=True)
**AttributeError: 'int' object has no attribute 'items'**
方法二:
def stats_text_en(text):
"""count english words in the text"""
replace_text=text.replace(',',' ').replace('.','').replace('!','').replace('*',' ').replace('-','').replace('?','')
split_text=replace_text.split()
wordcount={}
for i in split_text:
if i not in wordcount:
# if word is not in split_text, creat a new key and let counts be 1
# 疑问:如果word没在文本中,为什么其计数还是1呢?不应该是0么?
wordcount[i]=1
else:
# if words is in split_text, let counts added 1
wordcount[i]+=1
wordcount=sorted(wordcount.items(),key=lambda x:x[1],reverse=True)
return wordcount
#执行函数
text='''
python is interesting and learning is iinteresting too.'''
print(stats_text_en(text))
结果显示:
[('is', 2), ('interesting', 2), ('python', 1), ('and', 1), ('learning', 1), ('too', 1)]
疑问:
- 为何方法一不行呢?
- 方法一中的 # if……else#,与方法二中的“wordcount=split_text.count(i)” 区别是什么呢?
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the two stats_text_en examples included in the issue and trace how wordcount is assigned inside each loop. Explain why the first method changes the dictionary variable into an integer and how the counting approaches differ; done means answering both numbered questions with the shown outputs. No repository file or test is named.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100