在文本python中搜索特定单词

2024-10-02 18:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,它将接受一个词(或一组字符)以及语音的参数,并返回一个布尔表达式来表示单词是否存在,作为一个函数。在

speech2 = open("Obama_DNC.txt", "r")
speech2_words = speech2.read()
def search(word):
    if word in speech2_words:
        if len(word) == len(word in speech2_words):
            print(True)
        elif len(word) != len(word in speech2_words):
            print(False)
    elif not word in speech2_words:
        print(False)


word = input("search?")
search(word)

我想让程序在文本中搜索的单词与输入完全匹配,而不是另一个单词的一部分(“America”中的“America”)。我曾想过使用len()函数,但它似乎不起作用,我被卡住了。如果有人能帮我解决这个问题,那会很有帮助的。提前谢谢你


Tags: 函数infalsesearchlenif语音字符
2条回答

您也可以使用mmap,以获取有关mmap的更多信息

python3中的mmap与python2.7中的mmap处理方式不同

下面的代码是针对2.7的,它在文本文件中查找字符串。在

#!/usr/bin/python

import mmap
f = open('Obama_DNC.txt')
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
    print 'true'

Why mmap doesnt work with large files.

一种选择是在regex模块中使用findall()方法,该方法可用于查找特定字符串的所有出现。在

或者,您可以包括list.count(),以检查搜索的字符串在文本中出现的次数:

import re

def search(word):
    found = re.findall('\\b' + word + '\\b', speech2_words)
    if found:
        print(True, '{word} occurs {counts} time'.format(word=word, counts=found.count(word)))
    else:
        print(False)

输出:

^{pr2}$

相关问题 更多 >