python - 删除python中文本文件的下划线和连字符以外的所有符号
问题描述
我想删除输入文件的所有特殊字符(包括单个小写字母),除了具有下划线符号 (_) 和连字符 (-) 符号的单词(添加示例)使用或不使用正则表达式用于未展平列表(列表列表)?
有没有办法?
import re
from nltk import word_tokenize
from nltk.corpus import stopwords
data = {'fresh air', 'entertainment system', 'ice cream', 'blood pressure', 'body temperature', 'car', 'ac', 'air quality'}
data = {i: i.replace(" ", "_") for i in data}
pattern = re.compile(r"\b("+"|".join(data)+r")\b")
text_file = ['https://stackoverflow.com/questions', 'www.google.com/the pda', 'Z\'s is (vitamin-d) in (milk) 5 ml "enough", carrying? 321 active automatic body hi+al blood pressure.', 'body temperature [try] to improve air quality level by automatic intake of fresh air.', 'blood pressure monitor', 'I buy more ice cream', 'proper method to add frozen wild blueberries in ice cream']
sw0 = (stopwords.words('english'))
sw1 = ["i", "hi"]
sw=sw0+sw1
result = [pattern.sub(lambda x: "{}".format(data[x.group()]), i) for i in text_file]
tokens = [[word.lower() for word in word_tokenize(word)] for word in result]
filtered_tokens = [[token for token in sentence if (token not in sw)] for sentence in tokens]
print(filtered_tokens)
输入显示在代码中的文本文件中。
我希望输出只显示单词(保留一些中间有下划线的单词,如 body_temperature、blood_pressure、air_quality 等)。
我已经尝试并完成了使用regexp_tokenize
aregex pattern
并设置gaps = True
. 我想使用 nltk 来实现相同的目标word_tokenize
。任何帮助表示赞赏。
预期输出:
[['pda'], ['vitamin-d', 'milk', 'ml', 'enough', 'carrying', 'active', 'automatic', 'body', 'blood_pressure'], ['body_temperature', 'try', 'improve', 'air_quality', 'level', 'automatic', 'intake', 'fresh_air'], ['blood_pressure', 'monitor'], ['buy', 'ice-cream'], ['proper', 'method', 'add', 'frozen', 'wild', 'blueberries', 'ice_cream']]
解决方案
推荐阅读
- visual-studio - 在 Visual Studio 的代码中查看变更集作者
- r - 基于悬停在传单中的目的地(circleMarkers)上突出显示路线(折线)
- firebase - 为什么我可以将枚举保存到 Firestore,但是当我尝试检索它时它会使应用程序崩溃?
- javascript - 如何从innerHTML输出中删除引号
- python - 如果索引中的默认值为 0,为什么 Python 默认不在冒号“:”中考虑它
- vba - 如何从具有正则表达式匹配的 for each 循环中获取所有值并将其显示在电子邮件上?
- flutter - 在 TextFormFeild 任何解决方案 Flutter 中添加更多文本后显示空白
- c - 错误:分段错误,核心转储,在 c 编程中
- vba - Catia 列表框项目
- android - 如何为Android中的不同布局设置链中按钮的大小