【问题标题】:Clean up a scraped text string with Python使用 Python 清理抓取的文本字符串
【发布时间】:2018-05-12 11:36:52
【问题描述】:

我一直在尝试移除刮掉的绳子的不必要部分,但遇到了困难。我确信这很简单,但我可能缺乏寻找有效解决方案的术语。

我有我需要的所有信息,现在正在尝试创建一个干净的输出。我正在使用此代码...

for each in soup.findAll('div', attrs={'class': 'className'}):
    print(each.text.split('\n'))

输出是数字和带有可变空格的文本的混合,类似于...

['', '', '', '                    1                ', '  Text Example', '                        (4)']

我需要生成一个类似...的列表

['1', 'Text Example', '(4)']

也许甚至从数字 4 中删除括号“()”。

谢谢。

【问题讨论】:

  • 我尝试使用 split() 和 strip() 变体删除空格,但我无法找出我需要的组合。
  • text.strip() 不带参数删除空格、制表符、回车。如果你有列表,那么你有result = [x.strip() for x in your_list if x.strip() != '']
  • @furas 但是当我这样做时,它会不断拆分我需要的两个单词文本,例如。 ['文本','示例']。我需要他们在一起。
  • strip() 仅在末尾删除 - split() 将文本拆分为单词,因此不要使用它。

标签: python html string beautifulsoup


【解决方案1】:
clean = []
for each in soup.findAll('div', attrs={'class': 'className'}):
    clean.append([s.strip() for s in each.text.strip() if s.strip()])
print(clean)

应该做的,我把它放在哪里的完整代码......

更新:

由于有关于效率低下的评论,出于好奇,我在 py3 上计时了双条与嵌套列表。当人们说最好进行剖析时,似乎背后有一些东西......

%timeit [s.strip() for s in l if s.strip()]
1.83 µs ± 21.5 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

%timeit [i for i in (s.strip() for s in l) if i]
2.16 µs ± 24.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

数据量较大时结果与往常略有不同...

%timeit [s.strip() for s in l*1000 if s.strip()]
1.57 ms ± 85.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit [i for i in (s.strip() for s in l*1000) if i]
1.45 ms ± 16.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

【讨论】:

  • 我见过用过的,但我把它放在哪里。我正在学习,非常感谢您的帮助。
  • 只有带空格的字符串怎么样? if s 不会删除它。
  • true,在 if 中添加了一个 strip(),并没有真正测试过自己,但我想这适用于只有空格的字符串。如果你想处理其他角色,我可能会在之后把它放在它自己的循环中,这样更容易理解在哪里做了什么。
  • 这是低效的,因为你要剥离每个字符串两次
  • 是的,对此无可争辩,但并非世界上的所有事情都需要高效,欢迎您使用正则表达式解决方案或嵌套列表或其他您想到的东西。跨度>
【解决方案2】:

让我们将您的问题简化为基本的list

l = ['', '', '', '                    1                ', '  Text Example', '                        (4)']

然后使用list-comp:

[i for i in (s.strip() for s in l) if i]

得到你的结果:

['1', 'Text Example', '(4)']

【讨论】:

  • 我只是想说声谢谢。你帮了我很多忙。
猜你喜欢
  • 2014-08-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2012-01-15
相关资源
最近更新 更多