簡體   English   中英

替換python列表中的特定字符

[英]Replacing specific characters in python list

我有一個名為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]'但不能刪除'( )'中的字符串。

您可以將regex列表理解 regex一起使用:

import re

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

其中my_list是所提及的原始list new_list保留的最終值將是:

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

字符串上的replace方法將替換實際的子字符串。 您需要使用正則表達式:

import re
#...
line[i] = re.sub(r' (.*)', '', line[i])

一個簡單的正則表達式就可以解決問題。

import re
output = [re.split(r'[[(]', s)[0].strip() for s in your_list]

您可以使用re.sub而不是replace

import re
# your code here
lines[i] = re.sub(r' \(.*\)','', lines[i])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM