[英]How to find the some word in the text file
我有一个文件文本,我想用条件过滤文本中的一些单词:
1)长度相同且以相同字母开头
2)查找带有至少2个正确放置的字母的单词
例如:
词=鼓
文本
byres
brits
blurb
bulks
bible
debug
debut
并希望输出: ['bulks', 'bible']
与bulks
有“B”和“U”正确地放置和bible
有2 b
正确放置bubal
我的理想与开始的Lettre找到类的话找字长度相同,然后找到正确的单词第二条件,但是我编写代码以re
开头找到单词,但运行不正常
import re
with open('words.txt','r') as file:
liste = file.read()
word = re.findall('[b]\w+',liste)
print(word)
我的代码返回['byres','brits','bulks','but','bug']
如何解决它并找到单词流的情况
根据您的评论进行编辑。
这可能是您想要的:
#!/usr/bin/env python
def find_best_letter_matches(lines, target):
m = []
m_count = 0
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count > m_count:
m = []
m_count = count
if count == m_count:
m.append(line)
return m
def find_n_letter_matches(lines, target, n):
m = []
for line in lines:
count = sum(map(lambda x: x[0] == x[1], zip(line, target)))
if count >= n:
m.append(line)
return m
if __name__ == '__main__':
with open('text.txt', 'r') as f:
lines = f.read().split('\n')
best_matches = find_best_letter_matches(lines, 'bubal')
n_matches = find_n_letter_matches(lines, 'bubal', 2)
print('Best letter matches', best_matches)
print('At least 2 letters match', n_matches)
该函数逐个字母地将每一行与目标进行比较,并计算匹配数。 然后第一个返回匹配度最高的行的列表,第二个返回所有具有n
或更多字母的匹配项。
示例文本(添加bubal)的输出为:
Best letter matches ['bubal']
At least 2 letters match ['bulks', 'bible', 'bubal']
尝试这个
wordToSearch = "bubal"
singlesChar = list(wordToSearch)
finalArray = []
with open('words.txt','r') as file:
liste = file.readlines()
for each in liste:
each = each.rstrip()
fn = list(each)
flag = 0
for i in range(0,len(singlesChar)):
if(fn[i] == singlesChar[i]):
flag+=1
if(flag >= 2): finalArray.append(each)
print(finalArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.