我写了一个简短的Python脚本,它解析一个文本文件,以便提取出长度在4到8个字母之间的所有单词,然后将它们写入另一个文本文件。每个单词都应该用引号括起来,后面跟一个逗号。为了测试这个脚本,我从lorem ipsum生成器中抓取了一段文本。然而,输出与脚本的规格不一致。我将在下面的脚本输出中解释这些差异。
代码如下:
import re
with open('loremipsum.txt') as file:
lines = file.read()
blacklist = [" ", ",", "."]
step_1 = re.split('. | , | ', lines)
with open('ipsumWords.txt', 'w') as f:
for word in step_1:
if not word in blacklist:
if (len(word) > 3 and len(word) < 9):
f.write("'")
f.write(word)
f.write("'")
f.write(",")以下是输入文件的简短示例:
西瓜葫芦。后磅小牛、干草或鸭子是、工具棚马。在茄子里,有谷仓、粮车、栅栏、西葫芦、胡萝卜等金属废料。孔雀叫,驼鸟,猫头鹰。四季豆,驼鸟卡车。葫芦对着焊接设备发出嘟嘟声。苹果、鸭子、稻草、燕子、驼鸟、毛驴、干草钩黄瓜。四季豆,驼鸟卡车。将收割机、打包机、香菜、甜瓜混合在一起。
输出如下所示:
‘葫芦’,‘庞德’,‘小牛’,‘马’,‘茄子’,'quonse','grai','bins','grai','truck','quonse','shed',‘栅栏’,'gate','zucchin','carrot','scra','metal','Peacock','ostriche','owls','Kidne','bean','ostric','trucks','Gourd',‘'utter','weldin','equipmen','haybine','Apple','duck','straw','quai','ostriche','donkey','Kidne','bean','ostric','trucks','Combin','Harveste','swather','bale','haybin','parsley','melo',
输出有几个问题。我将为每一类问题举一个例子。1.有些单词,比如"pounder“,最后一个字母被截断了,变成了"pounde”。2.单词ostriches不仅被截断了s,如果拼写正确,它将有9个字母长
发布于 2019-11-18 10:51:25
您的主要问题是下面这行中的正则表达式:
step_1 = re.split('. | , | ', lines)请记住,正则表达式中的.表示“任何字符”,因此表达式.<space>表示“任何后面跟着空格的字符”。这就是为什么有些单词似乎被截断了:以ostriches为例,末尾的s与您的.<space>表达式匹配,因此字符串在该点被拆分,而ostriche位于拆分的左侧。
还要记住,空格很重要,所以表达式<space>,<space>将只匹配两边都有空格的逗号,这可能不是您的意思。
如果您想拆分句点、逗号和空格,则需要如下内容:
step_1 = re.split('[.,]? ')这将在空格上拆分单词,空格前面可以是.或,。
这会导致step_1具有以下值:
>>> step_1
['Gourds', 'watermelon', 'Post', 'pounder', 'calf', 'hay', 'or',
'duck', 'is', 'tool', 'shed', 'horse', 'In', 'eggplant', 'quonset',
'is', 'grain', 'bins', 'grain', 'trucks', 'quonset', 'pole', 'shed',
'with', 'fences', 'gates', 'zucchini', 'carrots', 'scrap', 'metal',
'Peacocks', 'baa', 'ostriches', 'owls', 'Kidney', 'beans', 'ostrich',
'trucks', 'Gourds', 'utters', 'at', 'welding', 'equipment', 'a',
'oink', 'oink', 'haybine', 'Apples', 'ducks', 'straw', 'quail', 'a',
'ostriches', 'donkey', 'hay', 'hook', 'cucumbers', 'Kidney', 'beans',
'ostrich', 'trucks', 'Combine', 'Harvester', 'swather', 'baler', 'as',
'haybine', 'parsley', 'melon', 'in', 'ha.\n']这应该会让你更接近你想要的。
https://stackoverflow.com/questions/58907298
复制相似问题