Python如何在列表中使用方法

2024-03-29 05:17:49 发布

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

我有一个方法来删除一个单词数组中每个单词的标点符号,我想用它来理解列表。我所能想到的基本Python知识是:

def remove_punctuation(sentence: str) -> str:
    return sentence.translate(str.maketrans('', '', string.punctuation))

def letters_only(astr):
return astr.isalpha()

def clean_text(docs):
    cleaned_docs = []
    for doc in docs:
        cleaned_docs.append(' '.join([lemmatizer.lemmatize(remove_punctuation(word.lower()))
                         for word in doc.split()
                         if letters_only(word)
                         and remove_punctuation(word) not in all_names
                         and remove_punctuation(word) not in all_names_lower]))
    return cleaned_docs

如你所见,我在很多地方使用“删除标点符号”方法。如果只使用一次或更有效,有什么方法可以使用吗?你知道吗

谢谢!你知道吗

*仅字母\u-它来自一些教程,不幸的是,它看到了“最佳”这个词在结尾加上感叹号并删除单词-bu我试图使它只删除感叹号。你知道吗


Tags: 方法indocsonlyreturndef单词sentence
2条回答

既然您提供了letters_onlyremove_punctuation的定义,我们现在可以说您的代码相当于:

[lemmatizer.lemmatize(word.lower())
                         for word in doc.split()
                         if letters_only(word) and word.lower() not in all_names_lower]

所以所有对remove_punctuation的调用都是无用的,因为只有在letters_only(word)这意味着word没有任何标点符号的情况下才进行调用。你知道吗


不是真的。最好是zip将原始列表与删除标点符号的生成器结合在一起:

original_words = doc.split()
no_punct_words = map(remove_punctuation, original_words)

cleaned_docs.append(' '.join([lemmatizer.lemmatize(no_punct_word.lower())
                         for word, no_punct_word in zip(original_words, no_punct_words) if letters_only(word)
                         and no_punct_word not in all_names
                         and no_punct_word not in all_names_lower]))

不管怎样,你的条件没有多大意义。如果if letters_only(word)条件为真,我希望remove_punctuationword什么也不做,这样您就可以删除它。你知道吗

还有:两个条件:

no_punct_word not in all_names and no_punct_word not in all_names_lower

可能会变成:

no_punct_word.lower() not in all_names_lower

顺便说一句:如果您要应用的条件应该始终应用于remove_punctuation(word),那么您可以做得更好:您可以map该函数:

no_punct_words = map(remove_punctuation, doc.split())
# ...
[lemmatizer.lemmatize(word.lower())
                         for word in no_punct_words if letters_only(word)
                         and word.lower() not in all_names_lower]

也许你可以用.lower()做同样的事情:

lower_no_punct_words = map(str.lower, map(remove_punctuation, doc.split()))
# ...
[lemmatizer.lemmatize(word)
                         for word in lower_no_punct_words if letters_only(word)
                         and word not in all_names_lower]

为了猜测其意图(代码似乎没有什么bug),我想说您应该擅长下面的内容。注意整个过程的懒惰,它应该使代码在内存消耗上不那么贪婪。你知道吗

def normalized_words_of(doc):
    for word in doc.split():
        if letters_only(word):
            yield remove_punctuation(word.lower())

def clean_text(docs):
    for doc in docs:
        yield ' '.join(word for word in normalized_words_of(doc) if word not in all_names_lower)

print(list(clean_text(['hi there, you', 'good bye - till next time'])))

相关问题 更多 >