python-3.x - 如何删除字典中的某些单词
问题描述
我有一个包含值作为列表的字典,每个列表都包含字符串。我想 1) 删除标点符号,不包括 @ 和 2) 删除列表中带有“@”的项目。然而,我似乎无法得到第二部分:
>>> dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
>>>
>>> def remove_rounds(data):
... import json
... import string
... ndata = {}
... punct = string.punctuation
... rpunct = punct.replace('@',"") # withold @
... for k,v in data.items():
... alist = []
... ndata[k] = []
... for word in data[k]:
... alist.append(word.strip(rpunct))
... ndata[k] = alist
... sdata = {}
... for k,v in ndata.items():
... sdata[k] = []
... blist = []
... for word in ndata[k]:
... if word.startswith('@'):
... blist = ndata[k].remove(word) # returns the list
... sdata[k] = blist
... return sdata
...
>>> remove_rounds(dat)
{'2008': None, '2010': None}
所以,这ndata
部分工作正常,我能够去除列表中的标点符号,但我似乎无法使用相同的逻辑来去除以“@”开头的单词。我也不明白为什么不能应用相同的逻辑。
解决方案
如果它以 开头,请避免附加单词@
:
dat = {'2008':['what!','@cool','#fog','@dddong'],'2010':['hey','@cute']}
def remove_rounds(data):
import string
ndata = {}
punct = string.punctuation
rpunct = punct.replace('@',"") # withold @
for k,v in data.items():
alist = []
ndata[k] = []
for word in data[k]:
if word.startswith("@"):
continue # ignore this word and continue with the next one
alist.append(word.strip(rpunct))
ndata[k] = alist
return ndata
print(remove_rounds(dat))
结果:
{'2008': ['what', 'fog'], '2010': ['hey']}
推荐阅读
- javascript - 在用户接受 GDPR 和使用 cookie 之前阻止快速会话设置会话 ID
- c# - 我可以发送 SCSIOP_WRITE,但总是在我的 SCSIOP_WRITE 之前发送 2 个 SCSIOP_READ_CAPACITY。我做错什么了吗?
- windows - 访问应用程序的共享文件夹,但不访问用户
- google-maps - 标记过多时自定义标记中断
- node.js - 我的节点服务器由于溢出而不断重启
- r - R中DNAStringset的子集列表
- macos - 从命令行使用 Homebrew 的 clang
- php - 如何从 MySQL 表中正确获取结果
- python - 有限的执行:不能为变量分配新值?
- command-line - 支持 GPU 加速和命令行的视频转换器