首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中解析文本时出现问题

在python中解析文本时出现问题
EN

Stack Overflow用户
提问于 2019-11-18 10:37:30
回答 1查看 36关注 0票数 0

我写了一个简短的Python脚本,它解析一个文本文件,以便提取出长度在4到8个字母之间的所有单词,然后将它们写入另一个文本文件。每个单词都应该用引号括起来,后面跟一个逗号。为了测试这个脚本,我从lorem ipsum生成器中抓取了一段文本。然而,输出与脚本的规格不一致。我将在下面的脚本输出中解释这些差异。

代码如下:

代码语言:javascript
复制
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个字母长

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-18 10:51:25

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

代码语言:javascript
复制
step_1 = re.split('. | , | ', lines)

请记住,正则表达式中的.表示“任何字符”,因此表达式.<space>表示“任何后面跟着空格的字符”。这就是为什么有些单词似乎被截断了:以ostriches为例,末尾的s与您的.<space>表达式匹配,因此字符串在该点被拆分,而ostriche位于拆分的左侧。

还要记住,空格很重要,所以表达式<space>,<space>将只匹配两边都有空格的逗号,这可能不是您的意思。

如果您想拆分句点、逗号和空格,则需要如下内容:

代码语言:javascript
复制
step_1 = re.split('[.,]? ')

这将在空格上拆分单词,空格前面可以是.,

这会导致step_1具有以下值:

代码语言:javascript
复制
>>> 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']

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58907298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档