【问题标题】:Remove paragraphs and saving everything to one line删除段落并将所有内容保存到一行
【发布时间】:2016-09-30 07:03:15
【问题描述】:

您好,我不知道如何解释,我有这个问题。目前我有一些文字如下所示:

 picture gallery 
    see also 
    adaptation
    ecology
    extreme environment clothing
    extremophile
    lexen life in extreme environments
    natural environment
    references 
    "extreme environment" microbial life np nd web 16 may 2013
    feminism and gis refers to the use of geographic information system gis for feminist research and also how women influence gis at technological stages feminist gis research is aware of power differences in social and economic realms
     history 

我的问题是我如何才能得到这样的结果,例如:

picture gallery see also adaptation ecology extreme environment clothing extremophile lexen life in extreme environments natural environment references "extreme environment" microbial life np nd web 16 may 2013 feminism and gis refers to the use of geographic information system gis for feminist research and also how women influence gis at technological stages feminist gis research is aware of power differences in social and economic realms

我不确定这叫什么,但到目前为止,我找到的解决方案是删除所有我不需要的空格。

请帮帮我。

谢谢。

【问题讨论】:

  • 首先是文件还是只是一些文本?
  • 您可以通过重新添加历史来更正结果 - 或明确指出,这应从输入中删除(最后一个字或历史,尤其是... ;-)
  • 抱歉回复晚了,是的,这是一个文件。
  • 好的,迟到总比没有好:) - 我更新了我的答案。这应该尽可能好(当文件的内容不超过可用 RAM 时......)

标签: python regex python-2.7


【解决方案1】:

如果是文件:

text = file('path/to/your/file.txt').read()
new_text = text.replace('\n', ' ')
print(new_text) # this will have no new lines
with open('output.txt', 'wr') as out:
    out.write(new_text) #this will write it to a file

你也可以使用正则表达式,就像 PJSCopeland 说的:

import re
s = "Example String \n more example string"
replaced = re.sub('\s+', ' ', s)
print replaced

Dilettant 的解决方案简洁、正确,而且比使用正则表达式更快(根据我的衡量),因此我建议将其作为最佳解决方案:

filtered = ' '.join(text.strip().split())

【讨论】:

  • 第一个也会替换换行符后的空格吗?第二个是否会替换所有实例,还是需要g 标志?
  • 第二个不需要 g 标志。根据您的第一个问题,不,它实际上需要在之后删除多个空格,很好地抓住@PJSCopeland。
【解决方案2】:

请注意,答案中给出的结果在右边距很有创意,它从输入数据中删除了历史;-) 更新:最新评论表明,数据来自文件,因此更新回答。

将此视为一个不需要的小故障,我建议既不使用正则表达式也不替换。只需像这样一次性完成剥离-拆分-连接转换(假设文本在您调用脚本的文件夹中的文件in.txt 中):

#! /usr/bin/env python

with open('in.txt', 'rt') as f:
    filtered = ' '.join(f.read().strip().split())

或者 - 如果已经在变量中(并且将期望和比较作为最小测试):

#! /usr/bin/env python

text = '''picture gallery 
    see also 
    adaptation
    ecology
    extreme environment clothing
    extremophile
    lexen life in extreme environments
    natural environment
    references 
    "extreme environment" microbial life np nd web 16 may 2013
    feminism and gis refers to the use of geographic information system gis for feminist research and also how women influence gis at technological stages feminist gis research is aware of power differences in social and economic realms
     history 
'''

expected = (
    'picture gallery see also adaptation ecology extreme environment'
    ' clothing extremophile lexen life in extreme environments'
    ' natural environment references "extreme environment" microbial'
    ' life np nd web 16 may 2013 feminism and gis refers to the use'
    ' of geographic information system gis for feminist research and'
    ' also how women influence gis at technological stages feminist'
    ' gis research is aware of power differences in social and'
    ' economic realms history')

filtered = ' '.join(text.strip().split())

assert filtered == expected

如果您需要在“单行”结果的末尾换行,您可以改为:

filtered = '%s\n' % (' '.join(text.strip().split()),)

filtered = ' '.join(text.strip().split()) + '\n'

在这种情况下,断言或预期变量当然应该同步更改;-)

这应该也是一个逻辑清晰的解决方案。正则表达式通常很诱人,但如果结果对于像这样的简单拆分连接管道是可行的,它们会导致一些运行时复杂性(以及嵌入的另一种语言)。

只需使用上述设置进行测量,并为正则表达式调整一个:

print 'strip-split-join:  ', ['%0.4f' % round(z, 4) for z in timeit.Timer("filtered = ' '.join(text.strip().split())", setup=setup).repeat(7, 1000)]
print 're.sub("\s+", " "):', ['%0.4f' % round(z, 4) for z in timeit.Timer("filtered = replaced = re.sub('\s+', ' ', text)", setup=setup_re).repeat(7, 1000)]

这给出(在我的机器上):

strip-split-join:   ['0.0043', '0.0045', '0.0047', '0.0046', '0.0043', '0.0040', '0.0045']
re.sub("\s+", " "): ['0.0265', '0.0254', '0.0246', '0.0248', '0.0238', '0.0255', '0.0266']

所以正则表达式解决方案慢了大约。 5 倍。

【讨论】:

  • 据我所知,我建议的解决方案都没有“删除历史”。我的第一个建议确实留下了很多讨厌的空间。正则表达式工作正常,它只是在最后留下一个额外的空间expected == replaced[:-1] 是真的使用它。我很想知道哪种解决方案更快——正则表达式还是这个。很高兴它是一行:)
  • @rofls:我认为它在逻辑上更简洁,即明确且速度快 5 倍左右 - 请参见。我更新的答案。考虑到 OP 似乎是她/他学习 python 的新手,正则表达式是一种复杂且令人沮丧的体验,例如。当出现一些拼写错误,需要转义等时。当已知基本解决方案时,最好使用正则表达式攻击更复杂的任务 - 稍后(IMO)。
  • Dilettant 这个解决方案是最快的。不是五分之一(根据我的测试),但它是最快的,所以我会推荐它。然后又是在我们的测试中导入re 模块的开销。无论如何,我怀疑 OP 需要最快,我同意您的解决方案更清晰;所以这可能是最重要的:)
【解决方案3】:

/\s+/g(至少一个空白字符的每个实例)替换为" "。 (不幸的是,我不熟悉 Python,所以我不知道方法调用会是什么。)

【讨论】:

  • re.sub(),来自re 模块:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
相关资源
最近更新 更多