gpt4 book ai didi

python - 代码不从字典中删除所需的值

转载 作者:太空宇宙 更新时间:2023-11-04 10:44:50 25 4
gpt4 key购买 nike

已链接 Removing escaped entities from a String in Python

我的代码正在读取一个大的推文 csv 文件并将其解析为两个字典(取决于推文的情绪)。然后,我创建了一个新字典并使用 HTML 解析器对所有内容进行了转义,然后使用 translate() 方法从文本中删除所有标点符号。
最后,我试图只保留大于 length = 3 的单词。
这是我的代码:

tweets = []
for (text, sentiment) in pos_tweets.items() + neg_tweets.items():
text = HTMLParser.HTMLParser().unescape(text.decode('ascii'))
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
shortenedText = [e.lower() and e.translate(remove_punctuation_map) for e in text.split() if len(e) >= 3 and not e.startswith(('http', '@')) ]
print shortenedText

然而,我发现虽然我想要的大部分内容都已完成,但我仍然得到长度为二(但不是长度为一)的单词,并且我的字典中有一些空白条目。
例如:

(: !!!!!! - so I wrote something last week
* enough said *
.... Do I need to say it?

产生:

[u'', u'wrote', u'something', u'last', u'week']
[u'enough', u'said']
[u'', u'need', u'even', u'say', u'it']

我的代码有什么问题?如何删除所有长度小于 2 的单词,包括空白条目?

最佳答案

我认为你的问题是,当你测试是否 len(e) >= 3 时,e 仍然包含标点符号,所以“它?”没有被过滤掉。也许分两步完成?清除标点符号,然后过滤大小?

有点像

cleanedText = [e.translate(remove_punctuation_map).lower() for e in text.split() if not e.startswith(('http', '@')) ]
shortenedText = [e for e in cleanedText if len(e) >= 3]

关于python - 代码不从字典中删除所需的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18148953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com