将解析的文本写入python3中的.csv文件时出现换行符/换行符问题

时间:2018-11-21 15:52:03

标签: python-3.x macos csv web-scraping beautifulsoup

使用BeautifulSoup从html解析提取的文本并将其写入.csv文件时遇到问题。

使用诸如标题日期描述信息

之类的数据来解析页面

我有一个说明文本示例,其示例具有从网页中解析的确切结构。它具有那些
标记和双空格:

<p>Hello World <br/>
<br/>
Key points <br/>
<br/>
 -  Point number one  <br/>
 -  Point number two    <br/>
 -  Point number three  </p>

因此我设法通过使用 .text.strip()将其提取为文本,现在是:

Hello World 

Key points 

 -  Point number one  
 -  Point number two    
 -  Point number three  

然后我想将结果保存到.csv文件,每个结果保存到一个新单元格:

Title, Date, Description, Info
Title, Date, Description, Info
Title, Date, Description, Info

为此,我要创建一个文件,设置标题并开始使用FOR循环将其写入其中

filename = "scraping.csv"
f = open(filename, "w")

headers = "Title, Date, Description, Info\n"
f.write(headers)
for article in articles:
    ...
    f.write(title + "," + date + "," + description + "," + info + "\n")
f.close()

最后,我得到的是带有所有信息的.csv文件。 问题是当说明传递到文件时,它会破坏所有行。

Title, Date, 
Des
crip
tion, Info
Title, Date, 
Des
crip
tion, Info    
Title, Date, 
Des
crip
tion, Info

如果我将文件中的所有内容(除了说明都很好)写入文件,

如何将这个说明保存到单元格中,并忽略所有不需要的换行符/换行符?

更新
根据 @ewwink 的建议,此组合有助于消除不必要的换行符

description = re.sub(r"[\r\n]+", " ", description)

不幸的是,它仅一行打印到.csv文件的单元格中,而没有格式化。但是我可以通过替换 \ r \ n

用不可见的稻草符号在.csv文件中换行
pilcrow = """
    """
description = re.sub(r"[\r\n]+", pilcrow, description)

1 个答案:

答案 0 :(得分:1)

要将其保存为.csv文件,您需要将双引号引起来,因此,如果存在,,它将不会破坏您的csv列并使用"转义""

for article in articles:
    ...
    # description = re.sub(r"[\r\n]+", " ", description)
    description = description.replace('"', '""')
    rows = '"%s","%s","%s","%s"\n' % (title, date, description, info)
    f.write(rows)