如何在Python列表中删除括号内的文本?

huangapple go评论70阅读模式
英文:

How to remove text between () in a python list?

问题

I am still quite unexperienced and hope you can help me. I have tried a lot of different approaches in order to remove some text between () in a python3 list, but I haven't been successful so far (tried e.g. regex, split, join replace, remove, lambda etc.).

#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.iban.com/country-codes')
soup = BeautifulSoup(data.text, "lxml")

output = [[cell.get_text(strip=True) for cell in row.find_all('td')[0:2]]
          for row in soup.find_all("tr")]

for i in range(1, len(output)):
    print('Name of country "' + (output[i][0]) + '"')
    print('Country code"' + (output[i][1]) + '"')
    print('')

This code produces the following output

Name of country "United States of America (the)"
Country code"US"

Name of country "Venezuela (Bolivarian Republic of)"
Country code"VE"

But I would like to remove all text between (), e.g. the "(the)" and "(Bolivarian Republic of)" in the above example output, so output would be

Name of country "United States of America"
Country code"US"

Name of country "Venezuela"
Country code"VE"

I am very sorry if this is an answer which has been answered before, but I haven't been able to find the answer to my question and I have been searching a lot before I gave up 如何在Python列表中删除括号内的文本?

英文:

I am still quite unexperienced and hope you can help me. I have tried a lot of different approaches in order to remove some text between () in a python3 list, but I haven't been successful so far (tried e.g. regex, split, join replace, remove, lambda etc.).

#!/usr/bin/python3

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.iban.com/country-codes')
soup = BeautifulSoup(data.text, "lxml")


output = [[cell.get_text(strip=True) for cell in row.find_all('td')[0:2]]
        for row in soup.find_all("tr")]

for i in range(1, len(output)):
	print('Name of country "' + (output[i][0]) + '"')
	print('Country code"' + (output[i][1]) + '"')
	print('')

This code produces the following output

Name of country "United States of America (the)"
Country code"US"

Name of country "Venezuela (Bolivarian Republic of)"
Country code"VE"

But I would like to remove all text between (), e.g. the "(the)" and "(Bolivarian Republic of)" in the above example output, so output would be

Name of country "United States of America"
Country code"US"
    
Name of country "Venezuela"
Country code"VE"

I am very sorry if this is an answer which has been answered before, but I haven't been able to finde the answer to my question and I have been searching a lot before I gave up 如何在Python列表中删除括号内的文本?

答案1

得分: 1

你可以简单地使用 .split() 通过 ( 进行分割,并从结果中提取第一个元素:

[e.split(' (')[0] for e in row.stripped_strings]

示例

不仅仅打印结果,还可以将其转换并以更有结构的方式存储,以便轻松转换为其他格式。

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.iban.com/country-codes')
soup = BeautifulSoup(data.text, "lxml")

d = []
for row in soup.select('table tbody tr'):
    d.append(
        dict(
            zip(
                soup.select_one('table tr:has(th)').stripped_strings,
                [e.split(' (')[0] for e in row.stripped_strings]
            )
        )
    )
print(d)

输出结果(美国)

{'Country': 'United States of America', 'Alpha-2 code': 'US', 'Alpha-3 code': 'USA', 'Numeric': '840'}
英文:

You could simply use .split() to split by ( and pick the first element from result:

[e.split(' (')[0] for e in row.stripped_strings]

Example

Instead of just printing the results, convert and store them in a more structured way, that could be easy transformed to other formats.

import requests
from bs4 import BeautifulSoup

data = requests.get('https://www.iban.com/country-codes')
soup = BeautifulSoup(data.text, "lxml")

d = []
for row in soup.select('table tbody tr'):
    d .append(
        dict(
            zip(
                soup.select_one('table tr:has(th)').stripped_strings,
                [e.split(' (')[0] for e in row.stripped_strings]
            )
        )
    )
print(d)

Output for US

{'Country': 'United States of America', 'Alpha-2 code': 'US', 'Alpha-3 code': 'USA', 'Numeric': '840'}

huangapple
  • 本文由 发表于 2023年3月15日 21:35:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定