Skip to main content
 首页 » 编程设计

python 的 .replace 留下空行

2025年05月04日17jpfss

我正在使用 scrapy 从网站中提取数据。纯粹的版本是这样的:

{eps: 25} 
{eps:[]} 
{eps:[]} 
{eps:[]} 
{eps: 50} 
{eps:[]} 
{eps:[]} 
{eps:[]} 

现在我不确定为什么会出现空白,但我可以使用 .replace 删除它们。问题是当我使用 .replace 结果是这样的:

25 
 
 
 
50 
 
 
 
# Code comment to show extra spaces. 

我试过 .split、.sub、.strip 都没有用。我不确定还能尝试什么。

更新:

添加源代码

# coding: utf-8 
from scrapy.spider import BaseSpider 
from scrapy.selector import HtmlXPathSelector 
from scrapy.contrib.exporter import CsvItemExporter 
import re 
import csv 
import urlparse 
from stockscrape.items import EPSItem 
 
class epsScrape(BaseSpider): 
        name = "eps" 
        allowed_domains = ["investors.com"] 
        ifile = open('test.txt', "r") 
        reader = csv.reader(ifile) 
        start_urls = [] 
        for row in ifile: 
                url = row.replace("\n","") 
                if url == "symbol": 
                        continue 
                else: 
                        start_urls.append("http://research.investors.com/quotes/nyse-" + url + ".htm") 
        ifile.close() 
 
        def parse(self, response): 
                f = open("eps.txt", "a+") 
                sel = HtmlXPathSelector(response) 
                sites = sel.select("//tbody/tr") 
                items = [] 
                for site in sites: 
                        item = EPSItem() 
                        item['eps']  = site.select("td[contains(@class, 'rating')]/span/text()").extract() 
                        strItem = str(item) 
                        newItem = strItem.replace(" ","").replace("'","").replace("{eps:[","").replace("]}","").replace("u","").replace("\\r\\n",'').replace('$ 
                        f.write("%s\n" % newItem) 
                f.close() 

text.txt 中有一个股票代码,如下所示:

MSFT 
A 
H 

等等等等

请您参考如下方法:

空行包含换行;也替换 \n。

如果您发现您最终要删除所有 换行符,则拆分换行符并删除任何空字符串值:

outputstring = '\n'.join([line for line in inputstring.splitlines() if line.strip()]) 

这会删除所有空行,并用新的换行符重新连接剩余的非空行。

如果您通过打印或写入文件来逐行生成输出,那么当该行为空时不打印或写入:

newItem = newItem.replace(.., ..) 
if newItem.strip(): 
    print newItem 
    f.write('{}\n'.format(newItem)) 

if 语句测试包含的不仅仅是空格的行。