在python中解析文本的问题

威利德

我编写了一个简短的 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(",")

这是输入文件的简短示例:

葫芦西瓜。Post pounder 小牛,干草或鸭子,工具棚马。在茄子中,quonset 是粮仓,粮车 quonset 杆棚,带栅栏门的西葫芦胡萝卜废金属。孔雀 baa 鸵鸟猫头鹰。芸豆鸵鸟车。葫芦对着焊接设备发出一声嘶吼。苹果鸭草,鹌鹑鸵鸟驴,干草钩黄瓜。芸豆鸵鸟车。结合收割机 swather,打包机作为 haybine 欧芹,哈瓜。

这是输出的样子:

'葫芦','磅','小牛','马','茄子','quonse','grai','bins','grai','truck','quonse','shed','fence ','门','西葫芦','胡萝卜','scra','金属','孔雀','鸵鸟','猫头鹰','肾','豆','鸵鸟','卡车', '葫芦'、'发声'、'焊接'、'设备'、'海宾'、'苹果'、'鸭子'、'稻草'、'鹌鹑'、'鸵鸟'、'驴'、'肾'、'豆','鸵鸟','卡车','组合','Harveste','swather','bale','haybin','欧芹','甜瓜',

输出有几个问题。我将针对每一类问题举一个例子。1. 像“pounder”这样的单词的最后一个字母被截断而变成了“pounde” 2. 鸵鸟这个词不仅被截断了s,如果拼写正确,它的长度会是9个字母

拉尔斯克

您的主要问题是这一行中的正则表达式:

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']

这应该让你更接近你想要的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章