代码之家  ›  专栏  ›  技术社区  ›  Nick Duddy

FeedParser,删除特殊字符并写入CSV

  •  0
  • Nick Duddy  · 技术社区  · 7 年前

    我遇到了一些问题。从昨晚开始我一直在寻找答案,但似乎找不到解决办法。我确实有一种感觉,在feedparser正在解析的内容和将其移动到CSV之间,我缺少了一些知识,但我还不知道该用谷歌搜索什么。

    1. 在创建新文件时,如何将作者、链接和标题写入新行?

    rssurls = 'http://feeds.feedburner.com/TechCrunch/'
    
    techart = feedparser.parse(rssurls)
    # feeds = []
    
    # for url in rssurls:
    #     feedparser.parse(url)
    # for feed in feeds:
    #     for post in feed.entries:
    #         print(post.title)
    
    # print(feed.entires)
    
    techdeets = [post.author + " , " + post.title + " , " + post.link  for post in techart.entries]
    techdeets = [y.strip() for y in techdeets]
    techdeets
    

    输出 :我获得了所需的信息,但.strip标记没有剥离。

    [Darrell Etherington,Spin推出首个城市认可的dockless http://feedproxy.google.com/~r/Techcrunch/~3/BF74UZWBinI/ Lawler有530万美元的资金,CarDash想改变你 http://feedproxy.google.com/~r/Techcrunch/~3/pkamfdPAhhY/ Miller,AlienVault插件在黑暗网络上搜索被盗密码 http://feedproxy.google.com/~r/Techcrunch/~3/VbmdS0ODoSo/ “,”卢卡斯 最新更新中出现颠簸, http://feedproxy.google.com/~r/Techcrunch/~3/j91jQJm-f2E/ ',...]

    2) 写入CSV

    import csv
    
    savedfile = open('/test1.txt', 'w')
    savedfile.write(str(techdeets) + "/n")
    savedfile.close()
    
    import pandas as pd
    df = pd.read_csv('/test1.txt', encoding='cp1252')
    df
    

    输出 : 输出是一个只有1行和多列的数据帧。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Aziz Alto    7 年前

    你就快到了:-)

    df = pd.DataFrame(columns=['author', 'title', 'link'])
    for i, post in enumerate(techart.entries):
        df.loc[i] = post.author, post.title, post.link
    

    然后您可以保存它:

    df.to_csv('myfilename.csv', index=False)
    

    >>> import feedparser
    >>> import pandas as pd
    >>>
    >>> rssurls = 'http://feeds.feedburner.com/TechCrunch/'
    >>> techart = feedparser.parse(rssurls)
    >>>
    >>> df = pd.DataFrame()
    >>>
    >>> df['author'] = [post.author for post in techart.entries]
    >>> df['title'] = [post.title for post in techart.entries]
    >>> df['link'] = [post.link for post in techart.entries]