统计 编写一个程序,查询little_women.txt文件中单词’the’一共出现了多少次。
时间: 2024-02-17 18:04:40 浏览: 21
好的,您可以使用以下Python代码实现:
```python
with open('little_women.txt', 'r') as f:
text = f.read()
# 将文本中的标点符号替换为空格
text = text.replace('.', ' ').replace(',', ' ').replace(';', ' ').replace('!', ' ').replace('?', ' ')
# 将文本分割成单词列表
words = text.split()
# 统计单词出现的次数
count = 0
for word in words:
if word.lower() == 'the':
count += 1
print("单词'the'一共出现了{}次。".format(count))
```
这段代码会读取文件`little_women.txt`中的内容,将文本中的标点符号替换为空格,然后将文本分割成单词列表。接着,它会遍历单词列表,统计单词`the`出现的次数,最终输出结果。
相关问题
练习10-6:统计 编写一个程序,查询little_women.txt文件中单词’the’一共出现了多少次
好的,以下是代码实现:
```python
filename = 'little_women.txt'
try:
with open(filename) as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
else:
# 统计单词'the'的出现次数
word = 'the'
word_count = contents.lower().count(word)
print(f"The word '{word}' appears {word_count} times in the file {filename}.")
```
注意,为了避免大小写造成的统计错误,我们使用了`lower()`方法将所有单词转换为小写字母。
编写程序,统计“小王子.txt”文件中,出现“little prince”的次数
以下是 Python 代码实现:
```python
# 打开文件
with open("小王子.txt", "r", encoding="utf-8") as f:
# 读取文件内容
content = f.read()
# 统计出现次数
count = content.count("little prince")
# 打印结果
print("出现次数:", count)
```
其中,`open()` 函数用于打开文件,`with` 语句可以确保在操作完成后自动关闭文件。`count()` 方法用于统计字符串中出现指定子字符串的次数。最后,输出统计结果。