python - 替换python列表中的特定字符

标签 python string algorithm pandas

我有一个名为 university_towns.txt 的列表,其中包含如下列表:

     ['Alabama[edit]\n',
        'Auburn (Auburn University)[1]\n',
        'Florence (University of North Alabama)\n',
        'Jacksonville (Jacksonville State University)[2]\n',
        'Livingston (University of West Alabama)[2]\n',
        'Montevallo (University of Montevallo)[2]\n',
        'Troy (Troy University)[2]\n',
        'Tuscaloosa (University of Alabama, Stillman College, Shelton State)[3]      [4]\n',
        'Tuskegee (Tuskegee University)[5]\n']

我想清理这个文本文件,将括号中的所有字符替换为 '' 。所以,我希望我的文本文件看起来像:

['Alabama',
 'Auburn',
 'Florence',
 'Jacksonville',
 'Livingston',
 'Montevallo',
 'Troy',
 'Tuscaloosa,
 'Tuskegee',
 'Alaska',
 'Fairbanks',
 'Arizonan',
 'Flagstaff',
 'Tempe',
 'Tucson']

我正在尝试按如下方式执行此操作:

import pandas as pd
import numpy as np
file = open('university_towns.txt','r')
lines = files.readlines()
for i in range(0,len(file)):
    lines[i] = lines[i].replace('[edit]','')
    lines[i] = lines[i].replace(r' \(.*\)','')

有了这个,我可以删除 '[edit]' 但我无法删除 '( )' 中的字符串。

最佳答案

您可以将 regexlist comprehension 表达式一起用作:

import re

new_list = [re.match('\w+', i).group(0) for i in my_list]
#       match for word ^             ^ returns first word 

其中 my_list 是问题中提到的原始 listnew_list 持有的最终值将是:

['Alabama', 
 'Auburn', 
 'Florence', 
 'Jacksonville', 
 'Livingston', 
 'Montevallo', 
 'Troy', 
 'Tuscaloosa', 
 'Tuskegee']

关于python - 替换python列表中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41240936/

相关文章:

java - NullPointerException 将子字符串从字符串添加到数组列表

c# - C# 和 C++ 中字符串操作的不同基准

在加权有向图中寻找权重最低的路径权重的算法

algorithm - 低效分治算法的复杂性

python - 石头剪刀布 - 在数学上获得胜利

python - 分别对 numpy 数组中的所有偶数列和奇数列求和

python - Mac OS X 上的 Boost.Python Hello World

python - Django 1.9无法连接到MySQL服务器(黑屏)

c - 在 C 中生成路径的最佳方法是什么?

algorithm - 在有向图上查找关联的源和目标