Regex从文件中返回一组单词,这些单词可以用作为参数传递的字母拼写(python)

2024-06-28 19:40:49 发布

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

我有一个单词列表,比如

name
age
abhor
apple
ape

我想通过传递一组随机的字母,比如'apbecd',在列表上执行regex

现在必须返回列表中包含这组字母的所有单词。你知道吗

例如:python retun_words.py apbelcdg

会回来的

ape
apple
age

到目前为止,我只能根据单词匹配返回单词。我怎样才能达到我上面提到的结果。 另外,如果有任何其他方法来实现结果,而不是regex请让我知道

提前谢谢


Tags: 方法namepyapple列表age字母单词
3条回答

我相信shellmode的方法需要一个小的修正,因为它不适用于被检查的字母与单词中的最后一个字母相同的情况,但是单词本身包含的字母不是来自字母列表。我相信这个代码会起作用:

import sys
word_list = ['name', 'age', 'abhor', 'apple', 'ape']
letter_list = sys.argv[1]

for word in word_list:
    for counter,letter in enumerate(word):
        if letter not in letter_list:
            break
        if counter == len(word)-1: #reached the end of word
            print word 

在这里,如果不想使用regex,使用set并返回项也是一种方法。你知道吗

string_list = ["name", "age", "abhor", "apple", "ape"]
allowed_characters = "apbelcdg"
character_set = set(allowed_charcters)
print [item for item in string_list if not set(item)-character_set]

这将为您提供附着到字符集的字符串列表。你知道吗

但是,如果regex是您最想要的,那么我们就开始:-)

from re import match
string_list = ["name", "age", "abhor", "apple", "ape"]
allowed_characters = "apbelcdg"
print [item for item in string_list if match('[%s]*$' % (allowed_characters), item)]

没有必要使用regex。以下代码起作用。你知道吗

import sys
word_list = ['name', 'age', 'abhor', 'apple', 'ape']
letter_list = sys.argv[1]

for word in word_list:
    for letter in word:
        if letter not in letter_list:
            break
        elif letter == word[-1]:
            print word

输出

[root@mbp:~]# python return_words.py apbelcdg
age
apple
ape

相关问题 更多 >