python - 如何在文本数据中制作重复单词的矩阵
问题描述
我想阅读一些文本文件并找出每个单词每行重复多少次?这是我的文本文件
- خواب خودرو چگونه محاسبه می گردد؟ برای دریافت آن چه باید كرد؟
- مهلت زمانی تامین قطعه پس از درخواست مشتری چند روز است؟
- 免费 带入
- قطعات در نمایندگی ها مختلف شهر متفاوت است؟
并制作这样的输出
line# word#1 word#2 word#3 ......
1 2 0 1
2 0 0 2
.
.
.
我想创建一个函数来执行此操作,我不能将 countvectorizer 函数用于波斯语
解决方案
例子:
line_counter = 1
with open("text.txt", "r") as opened_file:
lines = opened_file.readlines()
for line in lines:
repeated_elem = {}
words = line.split()
for word in words:
if word in repeated_elem:
repeated_elem[word] += 1
continue
repeated_elem[word] = 1
print("{line}. line. Words: {words}".format(line=line_counter, words=repeated_elem))
line_counter += 1
我的文本文件的内容:
hello hi aloha hello bye
one two three four five two
yes no yes no yes no yes
输出:
>>> python3 test.py
1. line. Words: {'hello': 2, 'hi': 1, 'aloha': 1, 'bye': 1}
2. line. Words: {'one': 1, 'two': 2, 'three': 1, 'four': 1, 'five': 1}
3. line. Words: {'yes': 4, 'no': 3}
推荐阅读
- json - Kotlin 中 JSONArray 中的 MutableList
- templates - Prestashop 1.6 - 存储在数据库和订单页面后,“已发货”模板中未显示跟踪号
- google-app-engine - App Engine:如何在本地导入 Datastore
- android - kWS Android Web 服务器无法打开 JSP 文件
- cmd - CMD 命令:Conjuction [wsgen: wsdl 和 inlineScemas]
- apache-spark - 您如何查看 pyspark 中为 Window 函数创建的分区大小?
- c++ - 错误:'operator*' 不匹配(操作数类型为 'QGenericMatrix<4, 4, float>' 和 'QGenericMatrix<4, 3, float>')
- php - 电报机器人不起作用:来自 webhook 的错误响应:找到 302
- html - 如何在angularjs的ng-options中使用json对象设置键和值
- javascript - 防止在 react-simple-maps 中出现蓝色路径矩形