删除奇怪字符的python

2024-04-20 01:54:51 发布

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

我试图删除任何包含奇怪字符的句子,比如下面有很多奇怪下划线的句子。你知道吗

sentence=='"____ __,_____________.._____________________"

我首先创建一个函数来发现这个奇怪的字符,如果是真的,我们忽略这个句子:

    def underscore_filter(s):
        return "____ __," in s

    filter_fn_list = [underscore_filter]

    for fn in filter_fn_list:
        if fn(sentence):
            filter_match = True
            break
        if filter_match == True:
            continue

所以真正的问题只在于功能部分:

 def underscore_filter(s):
     return "____ __," in s

我只是不明白,尽管在我的函数中返回了完全相同的下划线模式,但当我调用它时,该函数的输出总是false。有什么问题,我怎样才能重新编写这个代码?我仍然需要类似的格式。你知道吗

我在末尾添加了“continue”,因为我的代码实际上是在读取CSV文件的行。如果行中包含奇怪的字符,我将跳过该行。你知道吗


Tags: 函数intruereturnifdefmatchfilter
3条回答

我觉得你把事情弄得更复杂了。使用列表理解尝试以下更简单的替代方法:

# list of sentences we want to filter
sentences = ["abcd", "a____ __,", "sdf", "ghke_______kh"]

# list of patterns we want to filter out
bad_patterns = ["____ __,", "_______"]

# perform the filtering
filtered_sentences = [s for s in sentences 
    if not any(pattern in s for pattern in bad_patterns)]

打印生成的filtered_sentences列表会产生以下输出:

['abcd', 'sdf']

我认为问题在于这一行:

filter_fn_list=[underscore_filter(s)]

它的作用是将True或False返回到filter\u fn\u列表中。但是,我认为您需要列出一个函数列表,稍后可以在循环中调用这些函数。因此,您应该:

filter_fn_list=[underscore_filter]

您可以通过lambda实现这一点。你知道吗

def underscore_filter(s):
    return "____ __," in s

filter_match = False
sentence = "____ __,_____________.._____________________"

filter_fn_list = [ lambda s:underscore_filter(s) ]

for fn in filter_fn_list:
    if fn(sentence):
        filter_match = True
        break

print filter_match

顺便说一句,我不明白你为什么在循环中添加continue部分,在我看来这是完全没有必要的,所以我就放弃了它。你知道吗

相关问题 更多 >