python单词查询_python - 在文件中查找单词的出现

I am trying to find the count of words that occured in a file. I have a text file (TEST.txt) the content of the file is as follows:

ashwin programmer india

amith programmer india

The result I expect is:

{ 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1}

The code I am using is:

for line in open(TEST.txt,'r'):

word = Counter(line.split())

print word

The result I get is:

Counter({'ashwin': 1, 'programmer': 1,'india':1})

Counter({'amith': 1, 'programmer': 1,'india':1})

Can any one please help me? Thanks in advance .

解决方案

Use the update method of Counter. Example:

from collections import Counter

data = '''\

ashwin programmer india

amith programmer india'''

c = Counter()

for line in data.splitlines():

c.update(line.split())

print(c)

Output:

Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于英语单词查询,我们可以使用Python的顺序查找、折半查找和索引查找算法。 1. 顺序查找:顺序查找是一种最简单的查找算法,它从列表的第一个元素开始逐个比对,直到找到目标元素或者遍历完整个列表。在Python,可以使用for循环来实现顺序查找,代码如下: ```python def sequential_search(word_list, target): for i in range(len(word_list)): if word_list[i] == target: return i return -1 ``` 其,word_list是一个包含英语单词的列表,target是要查找的目标单词。如果找到目标单词,返回它在列表的索引;否则返回-1。 2. 折半查找:折半查找,也称为二分查找,是一种更高效的查找算法。它要求列表必须有序,然后每次将查找范围缩小一半,直到找到目标元素或者查找范围为空。在Python,可以使用递归函数来实现折半查找,代码如下: ```python def binary_search(word_list, target, start, end): if start > end: return -1 mid = (start + end) // 2 if word_list[mid] == target: return mid elif word_list[mid] > target: return binary_search(word_list, target, start, mid-1) else: return binary_search(word_list, target, mid+1, end) ``` 其,word_list是一个有序的英语单词列表,target是要查找的目标单词,start和end是查找范围的起始和结束索引。如果找到目标单词,返回它在列表的索引;否则返回-1。 3. 索引查找:索引查找是一种更加高效的查找算法,它将列表分成若干个块,并建立一个索引表,每个索引项包含一个块的起始位置和终止位置。然后在索引表查找目标单词所在的块,并在该块进行顺序查找。在Python,可以使用字典来实现索引查找,代码如下: ```python def index_search(word_list, target, index): for i in range(len(index)-1): if target >= index[i] and target < index[i+1]: start = index[i] end = index[i+1] break else: return -1 for i in range(start, end): if word_list[i] == target: return i return -1 ``` 其,word_list是一个有序的英语单词列表,target是要查找的目标单词,index是索引表,每个索引项包含一个块的起始位置和终止位置。如果找到目标单词,返回它在列表的索引;否则返回-1。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值