使用python从大小写的文档文件中获取特定单词

2024-05-15 15:36:28 发布

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

我想在.doc文件中获取一些单词,并将它们全部附加到列表中

文档文件内容: "i love Audi i love audi i love AuDi "

当我将奥迪或奥迪作为输入时,它应该读取所有这三种不同的“奥迪”,并返回包含所有三种不同奥迪的列表


Tags: 文件内容列表doc单词audilove
3条回答

尝试正则表达式,在其中查找word并忽略大小写

import re

doc_content = 'i love Audi i love audi i love AuDi and audis  but not audits or audiences'

results = re.findall(r'\baudi[s]?\b', doc_content, re.IGNORECASE) #The ? metacharacter will match only one 's' following audi to include the plural form and the \b at the end will exclude other words that begin with audi.

print(results)
['Audi', 'audi', 'AuDi', 'audis']

下面是Python中正则表达式的链接-https://docs.python.org/3/howto/regex.html

一个非常简单的解决方案是使用正则表达式

import re
string = "i love Audi i love audi i love AuDi"
result = re.findall('[A,a][U,u][D,d][I,i]', string)

print(result)
['Audi', 'audi', 'AuDi']
import re

doc_content = 'i love Audi i love audi i love AuDi... but not audis'

results = re.findall(r'\baudi\b', doc_content, re.IGNORECASE) #use \b at start and end to match whole word. This will exclude audis.

print(results)
['Audi', 'audi', 'AuDi']

这对我有用。我只是在找这个\b解决了我的问题。谢谢:)

相关问题 更多 >