在python中处理文本片段

2024-04-27 03:56:37 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗数据.txt包括大小写的单词。你知道吗

我需要lower case them all except for the upper-cased characters that appear in braces,它们紧跟在可以以小写或大写结尾的单词后面,但是在第一个大括号之前没有空格。 e、 g

CAT{TT} Dog{DD} Horse{AA}
Snail{LL} RAT{TT}
ANT{AA}

这些应转化为:

cat{TT} dog{DD} horse{AA}
snail{LL} rat{TT}
ant{AA}

首先,我将列表中的所有内容降低大小写,并将它们放在lcChar(代码如下)。然后我试着在大括号中找到小写的字符,这样我就可以再次将它们大写。你知道吗

作为一个python新手,我陷入了下面的代码中。这只给出了大括号中的第一项。我还假设我需要另一个循环,以便将大括号中出现的所有项都大写。有什么帮助,请让我能够理解处理这些问题的最佳方法?你知道吗

import re
f = open(r'C:\Python27\MyScripts\Data.txt')
for line in f:
    lcChar = (line.lower())

patFinder1 = re.compile('{[a-z]+}')
findPat1=re.findall(patFinder1, lcChar)

Tags: 代码inretxtfor大括号单词lower
2条回答

re.subre.subn允许第二个参数是函数。Match对象被传递到该函数中,函数返回的任何内容都用于替换。你知道吗

这是我的看法:

import re

def manip(m):
    return m.groups()[0].lower()

data = ['CAT{TT} Dog{DD} Horse{AA}',
        'Snail{LL} RAT{TT}',
        'ANT{AA}']

for line in data:
    new_line = re.sub(r'((?:[^{]|^)[A-Z]+(?:[^}]|$))', manip, line)
    print new_line

产生:

cat{TT} dog{DD} horse{AA}
snail{LL} rat{TT}
ant{AA}

我本可以用lambda来代替,但这可以说不太清楚。你知道吗

直截了当的方法:

import re

regex = re.compile('([^}]*?{)')
str_ = '''CAT{TT} Dog{DD} Horse{AA}
Snail{LL} RAT{TT}
ANT{AA}'''

new_str =  re.sub(regex, lambda match: match.groups()[0].lower(), str_)
assert new_str == '''cat{TT} dog{DD} horse{AA}
snail{LL} rat{TT}
ant{AA}'''

print new_str

说明:

我使用regex只匹配需要小写的内容:

enter image description here

然后我将结果循环并替换为小写版本。你知道吗

编辑:使用sub替换更多优化版本。你知道吗

相关问题 更多 >