帮我写一段python程序统计一个txt文件中单词apple的出现的次数,并且输出每一行中单词apple出现的位置索引
时间: 2024-01-08 08:04:37 浏览: 27
好的,以下是一个Python程序,可以读取一个文本文件并统计单词 "apple" 出现的次数,并输出每一行中单词 "apple" 出现的位置索引:
```python
with open('filename.txt', 'r') as file:
count = 0
for i, line in enumerate(file):
if 'apple' in line:
count += line.count('apple')
print(f"第 {i+1} 行中单词 'apple' 出现的位置索引为: {[j for j in range(len(line)) if line.startswith('apple', j)]}")
print(f"单词 'apple' 出现的总次数为: {count}")
```
请将 `filename.txt` 替换为您要读取的文本文件的实际文件名。该程序首先遍历文件的每一行,使用 Python 的 `count()` 方法计算单词 "apple" 在每一行中出现的次数,并输出每一行中单词 "apple" 出现的位置索引。最后,程序输出单词 "apple" 在整个文本中出现的总次数。
相关问题
帮我写一段python程序统计一个txt文件中单词apple的出现的次数
当然可以,以下是一个简单的Python程序,可以读取一个文本文件并统计单词 "apple" 出现的次数:
```python
with open('filename.txt', 'r') as file:
text = file.read()
count = text.count('apple')
print(f'单词 "apple" 出现的次数为: {count}')
```
请将 `filename.txt` 替换为您要读取的文本文件的实际文件名。该程序将打开文件,并读取其中的文本,然后使用 Python 的 `count()` 方法计算单词 "apple" 在文本中出现的次数,并将结果打印到屏幕上。
帮我写一个Python程序,关于统计英文中单词出现的次数并按降序输出。
当然可以,以下是代码实现:
```python
import string
# 打开文件
with open("file.txt", "r") as file:
data = file.read().lower() # 转换为小写字母
# 去掉标点符号
data = data.translate(str.maketrans("", "", string.punctuation))
# 将字符串转换为单词列表
words = data.split()
# 统计单词出现次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 按降序输出单词及出现次数
for word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):
print(word, count)
```
其中,我们首先打开文件,然后将文件中的所有字母转换为小写字母,去掉标点符号,将字符串转换为单词列表。接着,我们使用字典来统计每个单词出现的次数。最后,我们按降序输出单词及其出现次数,使用 `sorted` 函数和 `lambda` 表达式来实现。