Python搜索文本文件并计算指定字符串的出现次数 [英] Python search text file and count occurrences of a specified string

查看:41
本文介绍了Python搜索文本文件并计算指定字符串的出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 python 搜索文本文件并计算用户定义的单词出现的次数.但是,当我在下面运行我的代码而不是获取该唯一词在文件中出现的次数的总和时,我得到了该文件中包含该词的行数的计数.

I am attempting to use python to search a text file and count the number of times a user defined word appears. But when I run my code below instead of getting a sum of the number of times that unique word appears in the file, I am getting a count for the number lines within that file contain that word.

示例:bob"这个词在文本文件中出现了 56 次,出现在 63 行文本中的 19 行.当我运行我的代码时,控制台会打印19".

Example: the word 'bob' exists 56 times in the text file, appearing in 19 of the total 63 lines of text. When I run my code the console prints '19'.

我猜我需要对我的 split 方法做一些不同的事情?我正在运行 Python 2.7.10.

I am guessing I need to do something different with my split method? I am running Python 2.7.10.

user_search_value = raw_input("Enter the value or string to search for: ")

count = 0    

with open(file.txt, 'r') as f:
    for word in f.readlines():
        words = word.lower().split()
        if user_search_value in words:
            count += 1
    print count

推荐答案

如果指定字符串"是一个带空格的短语,这里是一个有效的:

If the "specified string" is a phrase with spaces, here is one that works:

#!/usr/bin/python

import sys
import os

def count_words_in_file(filepath, words, action=None):
    with open(filepath) as f:
        data = f.read()
        for key,val in words.items():
            print "key is " + key + "\n"
            ct = data.count(key)
            words[key] = ct
        if action:
             action(filepath, words)


def print_summary(filepath, words):
    print(filepath)
    for key,val in sorted(words.items()):
        print('{0}:\t{1}'.format(
            key,
            val))


filepath = sys.argv[1]
keys = ["Hello how are you",
"Another phrase with spaces",
"A phrase with spaces and some punctuation."]
words = dict.fromkeys(keys,0)

count_words_in_file(filepath, words, action=print_summary)

这篇关于Python搜索文本文件并计算指定字符串的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆