如何在课文中找到some单词

2024-05-17 09:53:31 发布

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

我有一个文件文本,我想用条件过滤文本中的一些单词:

1)长度相同,以同一个字母开头

2)找出至少有2个字母正确放置的单词

例如:

word=巴巴尔

文本

byres
brits
blurb
bulks
bible
debug
debut

并希望输出:['bulks', 'bible']bulks正确放置'b'和'u',biblebubal正确放置2b 我的理想是找到一个以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'] 如何修复并找到词流条件


Tags: 文件代码文本re字母条件单词bible
2条回答

根据您的评论编辑。

这可能就是你想要的:

#!/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)                

相关问题 更多 >