简体   繁体   English

返回包含字母的单词列表

[英]Return a list of words that contain a letter

I wanna return a list of words containing a letter disregarding its case.我想返回一个包含字母的单词列表,不考虑大小写。 Say if i have sentence = "Anyone who has never made a mistake has never tried anything new" , then f(sentence, a) would return假设我有sentence = "Anyone who has never made a mistake has never tried anything new" ,那么f(sentence, a)将返回

['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']

This is what i have这就是我所拥有的

import re 
def f(string, match):
    string_list = string.split()
    match_list = []
    for word in string_list:

        if match in word:
            match_list.append(word)
    return match_list

You don't need re .你不需要re Use str.casefold :使用str.casefold

[w for w in sentence.split() if "a" in w.casefold()]

Output:输出:

['Anyone', 'has', 'made', 'a', 'mistake', 'has', 'anything']

如果没有标点符号,您可以使用字符串拆分。

match_list = [s for s in sentence.split(' ') if 'a' in s.lower()]

Here's another variation :这是另一个变化:

sentence = 'Anyone who has never made a mistake has never tried anything new'

def f (string, match) :
    match_list = []
    for word in string.split () :
        if match in word.lower ():
            match_list.append (word)
    return match_list

print (f (sentence, 'a'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在包含相同首字母python的列表中查找单词 - How to find words in a list that contain the same first letter python 给定字符串和(列表)单词,返回包含字符串的单词(最优算法) - Given string and (list) of words, return words that contain string (optimal algorithm) 如何计算列表中包含特定字母的单词数量? - How do I count the amount of words in a list which contain a specific letter? 查找字符串中仅包含一个字母的单词 - Finding words that contain all but one letter in string 使用过滤器从以目标字母开头的单词列表中返回单词 - Use filter to return the words from a list of words which start with a target letter Python:如何在句子的单词列表中找到一个字母并以原始大小写返回这些单词(大写/小写) - Python: How to find a letter in a sentence's list of words and return those words in their original case (upper/lower) 以两个包含单词的列表作为输入,以形成包含两个单词的元组,每个列表中的一个单词的起始字母相同 - Taking two lists as input that contain words, to form a tuple with two words, one from each list that have the same starting letter of each word 从单词列表中逐个字母打印 - Print letter by letter from a words-list 返回包含 Python 中 2 个单词的字符串 - Return string that contain 2 words in Python 如何获取字符串并返回字典中与该单词相差一个字母的所有单词的列表? - How to take a string and return a list of all the words in a dictionary that differ from this word by exactly one letter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM