Python - 多行连接困难,不依赖于“\n”

2024-09-30 23:35:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用beautifulsoup查找网页上的所有位置,它确实如此。你知道吗

get_location = second_soup.find_all('span', attrs={"class": "location"})
for local in get_location :
  if local:
    s = local.text
    s = s.replace("\n", "")
    s = s.replace("-", "") #removes the -
    s = s.split("|", 1)[0] #removes | and everything after it
    s = ''.join([i for i in s if not i.isdigit()]) #removes numbers from zip
    s = s.lstrip() #removes spaces
    s = s.rstrip() #removes spaces
    print(s)

我得到以下结果:

New York, NY
Brooklyn, NY
Johnville, KY

但是,我需要这样:

New York, NY, Brooklyn, NY, Johnville, KY

我尝试过的事情:

1)使用s.replace("\n", ", ")代替s.replace("\n", "")

结果是相同的,除了被替换为,之外,所以我得到:

, New York, NY, 
, Brooklyn, NY, 
, Johnville, KY, 

2)拆卸、更换和使用s = '\n'.join([line.strip() for line in s])

结果很奇怪,我每行只有一个字符。例如:

N
E
W


Y
O
R
K

编辑

我之所以需要它在一行中,是因为我要把它插入一个数组,而我不能在一个数组中插入多行,所以我得到了New York, NY,就这样。你知道吗

这就是我想要的数组:

['New York, NY, Brooklyn, NY, Johnville, KY', 'Boston, MA, Miami, FL']


Tags: innewforgetiflocallocation数组
3条回答

我无法测试,因为我们没有您的数据,但我认为您需要以下内容:

get_location = second_soup.find_all('span', attrs={"class": "location"})
rebuilt = []
for local in get_location :
    if local:
        s = local.text
        s = s.replace("\n", "")
        s = s.replace("-", "") #removes the -
        s = s.split("|", 1)[0] #removes | and everything after it
        s = ''.join([i for i in s if not i.isdigit()]) #removes numbers from zip
        s = s.strip() #removes spaces
        rebuilt.extend(s)
print(rebuilt)

在'if'循环的最后一行-print中,因为每一行都是用print的'end'参数打印的,设置为default='\n'。因此,它在下一行为每个循环打印。 因此,如果您将参数设置为逗号(,)或根据您的选择,则输出将打印在同一行中。 试试这个:

print(s, end=',')

可以执行以下操作以逗号替换换行符:

s = ', '.join(s.split('\n'))

但是,如果您能提供一个您正在处理的示例数据blob,这将是很有帮助的。你知道吗

相关问题 更多 >