从“ [”到末尾删除部分字符串

以下是我的文本文件的摘要:

import re 
f = open('/Users/name/Desktop/university_towns.txt',"r")
f.readlines()

Langston (Langston University)[5]
Norman (University of Oklahoma)[1]
Stillwater (Oklahoma State University)[5]
Tahlequah (Northeastern State University)[2]

我试图从每行中删除“ [2]”部分([之后的字符):

for i in f.readlines():
    i.replace('\[.*?\]',"")

但是**没有成功。

有人可以帮我吗?

评论
龙舌兰
龙舌兰

It should work without trailing /, I trid with regex sub,

import re
regex = r"\[.*?\]"
test_str = ("Langston (Langston University)[5]\n"
    "Norman (University of Oklahoma)[1]\n"
    "Stillwater (Oklahoma State University)[5]\n"
    "Tahlequah (Northeastern State University)[2]")

subst = ""
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
    print (result)
点赞
评论
Alex55
Alex55

We can try using re.sub here:

for i in f.readlines():
    print(re.sub(r'\[\d+\]$', '' , i))

This assumes that nothing would following the [num] tags occurring at the end of each line. If some other content could follow, the above pattern would have to be adjusted.

点赞
评论