python技术统计文件A.txt中出现的词的个数
时间: 2023-06-07 18:10:19 浏览: 101
您好,关于统计文件中词的个数的问题,我可以为您提供如下Python代码:
```
with open('A.txt', 'r') as f:
text = f.read()
words = text.split()
print(len(words))
```
该代码会打开A.txt文件并读取其中的内容,然后使用split()函数将文本分割成单个单词,并统计单词个数输出。
希望对您有所帮助,如果您还有其他问题,请随时提出。
相关问题
请使用python技术统计文件A.txt中出现的词的个数(字数>2),并把结果保存到文件B.txt
Sure, 我可以使用Python技术完成这个任务。以下是代码:
```python
# 打开文件A.txt,并且读取文件内容。
with open('A.txt', 'r') as file:
content = file.read()
# 把文件内容转换成小写,用空格分隔。
words = content.lower().split()
# 移除单个字符、数字和标点符号
words = [word for word in words if len(word) > 2 and not word.isdigit() and not any(char.isdigit() or char in ".,;:'\"?!()[]{}|-_/\\") for char in word]
# 统计每个单词出现的次数
word_count = {}
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 打开文件B.txt并保存结果
with open('B.txt', 'w') as file:
for word, count in word_count.items():
file.write(word + ': ' + str(count) + '\n')
```
代码会打开A.txt文件,读取其中的内容,然后把内容转换成小写,用空格分隔。接下来,移除单个字符、数字和标点符号(我们只算字母数量大于2的单词),然后统计单词出现的次数,并且把结果存储到一个字典中。最后,打开B.txt文件,并把字典中的结果写入到文件中。
请注意,代码中的一些特殊字符,因此请确保在使用代码的时候进行复制。
请使用python技术统计文件A.txt中出现的词的个数(字数>2),并把结果保存到文件B.txt中去。
好的,这个问题很简单,是属于技术问题。我可以用Python编写程序来进行统计和处理,代码如下:
```python
# 打开文件A.txt,统计每个单词的出现次数
word_dict = {}
with open('A.txt', 'r', encoding='UTF-8') as f:
for line in f.readlines():
words = line.strip().split()
for word in words:
if len(word) > 2:
if word not in word_dict:
word_dict[word] = 1
else:
word_dict[word] += 1
# 将结果写入文件B.txt
with open('B.txt', 'w', encoding='UTF-8') as f:
for k, v in word_dict.items():
f.write(k + ' ' + str(v) + '\n')
```
这个代码会读取文件A.txt中的每一行,将每行单词按空格切分,对每个单词进行长度判断,如果长度大于2,则统计该单词的出现次数,最后将结果写入文件B.txt中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)