首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在字符串中按特定顺序查找特定字符。Python

如何在字符串中按特定顺序查找特定字符。Python
EN

Stack Overflow用户
提问于 2021-07-10 23:38:13
回答 1查看 33关注 0票数 0

我有一个包含字典中所有单词的csv,并且我想有一个函数,它给定三个字符,按照给定的顺序从csv中搜索包含给定字符的所有单词。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2021-07-11 00:17:06

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

代码语言:javascript
复制
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)

获取words_with_a_b_c

代码语言:javascript
复制
['hello']
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68329183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档