【问题标题】:How to remove \n from the middle of texts in a list of texts in python如何从python文本列表中的文本中间删除\ n
【发布时间】:2016-02-21 21:21:06
【问题描述】:

我从网页中抓取了一个标题列表,在源代码中采用以下形式:

<h2 class="story-heading"><a href="somelink.html">Crash Highlights
Indonesia’s Poor Air
Safety Record</a><span class="product-label theme-nyt-now "><span class="visually-hidden">NYT Now</span><i class="icon dot-logo-icon"></i></span></h2>

我只想要文字。

我得到以下列表:

[u'Crash Highlights\nIndonesia\u2019s Poor Air\nSafety RecordNYT Now', u'Palestine Joins\nHague Criminal\nCourt, Risking\nU.S. SanctionsNYT Now', ... ]

每个字符串都有"\n" 字符并以"NYT Now" 结尾 我现在如何删除NYT?据我了解,get_text() 应该只检索&lt;a&gt; 选项卡内的函数

这是我的代码:

url="<website link>"
html = urllib2.urlopen(url)
soup = BeautifulSoup(html,'lxml')

headings_list=[]

for heading in soup.find_all(class_="story-heading"):
    for text in heading.find_all('a'):
        headings_list.append(heading.get_text().strip())

print headings_list

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    我认为这应该可以满足您的需求:

    heading.get_text().replace('\n',' ').replace('NYT Now', '')
    

    【讨论】:

    • 这个效果最好。谢谢!我还在末尾添加了一个 strip() 以删除任何前导或结尾的空格。
    • 实际上这会以意想不到的方式改变诸如“NYT Now Will Offer API for Web CrawlersNYT Now”之类的标题。更好地结合heading.get_text().replace('\n',' ')[0:-7]中的答案
    【解决方案2】:

    使用

    headings_list.append(heading.get_text().strip()[:-7])
    

    获取没有最后 7 个字符的标题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多