如果满足条件,是否从字符串中删除单词?

2024-09-30 18:21:32 发布

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

我需要在一系列的弦上做些“清洁”。 1要删除的特殊字符(如!@#$%^等) 2字符串中的所有单词都应使用小写字母 三。如果单词<;=2个字符,请删除该单词。(“a,it,me,us”等)

trainset = [('It is too bad that our jane is just a pigeon. It would be great if it could speak. It would be able to prove my innocence.'), ('I have no other choice. Is death the only way to prove it? Loving you is really hard!'), ('These are my last words.')]

def cleanedthings(trainset):
cleanedtrain = []
specialch = "!@#$%^&*-=_+:;\".,/?`~][}{|)("
for line in trainset:
    for word in line.split():
        lowword = word.lower()
        for ch in specialch:
            if ch in lowword:
                lowword = lowword.replace(ch,"")
        if len(lowword) >= 3:
            cleanedtrain.append(lowword)
return cleanedtrain

上面的功能似乎不起作用。。你能帮助我吗?而且,我需要最终的输出是字符串格式,而不是列表格式。你知道吗


Tags: to字符串inforifisitbe
1条回答
网友
1楼 · 发布于 2024-09-30 18:21:32

检查缩进和语法。逻辑是好的。你知道吗

trainset = [('It is too bad that our jane is just a pigeon. It would be great if it could speak. It would be able to prove my innocence.'), ('I have no other choice. Is death the only way to prove it? Loving you is really hard!'), ('These are my last words.')]

def cleanedthings(trainset):
    cleanedtrain = []
    specialch = "!@#$%^&*-=_+:;\".,/?`~][}{|)("
    for line in trainset:
        for word in line.split():
            lowword = word.lower()
            for ch in specialch:
                if ch in lowword:
                    lowword = lowword.replace(ch,"")
            if len(lowword) >= 3:
                cleanedtrain.append(lowword)
    return cleanedtrain

print " ".join(cleanedthings(trainset))

相关问题 更多 >