Skip to main content
 首页 » 编程设计

python之在 Python 中删除括号中的文本

2025年05月04日20dudu

我已经在 Python 中导入了一个 csv 文件。我正在尝试删除该文件中括号中的文本。

我写了下面的代码:

import csv 
 
 
with open('example.csv', 'r') as csv_file: 
    csv_reader = csv.reader(csv_file) 
 
#for line in csv_reader: 
    #print(line) 
 
 
    def a(test_str): 
        ret = '' 
        skip1c = 0 
        skip2c = 0 
        for i in test_str: 
            if i == '[': 
                skip1c += 1 
            elif i == '(': 
                skip2c += 1 
            elif i == ']' and skip1c > 0: 
                skip1c -= 1 
            elif i == ')' and skip2c > 0: 
                skip2c -= 1 
            elif skip1c == 0 and skip2c == 0: 
                ret += i 
        return ret 
 
        x = csv_reader 
        x = a(x) 
    for line in csv_reader: 
        print(line) 

这是我输出的几行:

['CompanyA (CA)'] 
['CompanyB'] 
['CompanyC'] 
['CompanyD (CD)'] 
['CompanyE (CE)'] 

如您所见,括号中的文字仍然存在。该代码似乎不适用于该文件。

我想删除括号中的整个单词。例如,“CompanyA (CA)”的输出应该只是CompanyA,而不是CompanyA CA。

以下是上述部分代码的示例,它确实提供了预期的结果。

    def a(test_str): 
ret = '' 
skip1c = 0 
skip2c = 0 
for i in test_str: 
    if i == '[': 
        skip1c += 1 
    elif i == '(': 
        skip2c += 1 
    elif i == ']' and skip1c > 0: 
        skip1c -= 1 
    elif i == ')'and skip2c > 0: 
        skip2c -= 1 
    elif skip1c == 0 and skip2c == 0: 
        ret += i 
return ret 
 
x = "ewq[a [(b] ([c))]] This is a sentence. (once a day) [twice a day]" 
x = a(x) 
print x 
print repr(x) 

这是该代码的输出:

    ewq This is a sentence.   

如有任何帮助,我们将不胜感激。 感谢您的宝贵时间:)

请您参考如下方法:

您可以使用正则表达式来做到这一点。下面的代码应该可以工作。

import re 
 
input_text = 'ewq[a [(b] ([c))]] This is a sentence. (once a day) [twice a day]' 
print re.sub(r'[\(\[]+.*?[\)\]]+', '', input_text) 

以上代码适用于任何输入。请在下面的代码中找到第一 block 中的输入。

csv_reader = ['CompanyA (CA)', 'CompanyC', 'CompanyD (CD)'] 
 
for line in csv_reader: 
    print re.sub(r'[\(\[]+.*?[\)\]]+', '', line)