如何在字符串中按特定顺序查找特定字符python

jhkqcmku  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(347)

我有一个包含字典中所有单词的csv,我想有一个函数,可以指定三个字符,搜索csv中按给定顺序包含给定字符的所有单词。

def read_words(registro):
    with open(file, encoding="utf-8") as f:
        lector = csv.reader(f)
        palabras = [p for p in lector]
    return palabras

file= ("Diccionario.csv")

register = read_words(file)

def search_for_words_with(register, a, b, c):
    res = []
    for w in register:
        if a in w:
            if b in w:
                if c in w:
                    res.append(w)
    return res
e1xvtsh3

e1xvtsh31#

使用正则表达式和列表理解:

import regex as re

def search_for_words_with(register, a, b, c):
    words_with_a_b_c = [w for w in register if re.search(a + '.*' + b + '.*' + c, w)]
    return words_with_a_b_c

register = ['hello', 'worldee']
a, b, c = 'e', 'l', 'o'

words_with_a_b_c = search_for_words_with(register, a, b, c)

用字母a_b_c获取单词

['hello']

相关问题