找到&改变字符串

时间:2014-04-12 12:42:01

标签: python python-2.7 text-processing text-parsing

我想知道如何在Python中更改字符串的某个部分。我是文本处理和Python的初学者。我花了两个小时才拿出下面的代码,但它不起作用。你能告诉我为什么吗?

我需要执行以下操作:словобword - > словоN[б]字

这是我到目前为止所拥有的:

# f is the input file, unformatted, anouns is the output file. Right now i get anouns=f,
# i.e. no changes are made to the lines written into anouns.  

def toNoun(matchobj):
    if matchobj.group(0) == ' б ': return ' N[б] '
    elif matchobj.group(0) == ' д ': return ' N[д] '
    elif matchobj.group(0) == ' в ': return ' N[в] '
    else: return 'N[й]'

lines = f.readlines() # list of lines

for line in lines:
   if re.match(ur"(?u)^.* ([бдв]|й){1} .*", line):
     anouns.write(re.sub(' [бдв]|й ',toNoun,line))

从输入文件:

aбаде©Ewigkeit f

字母n

aвстриховÖsterreicherm

Wiege f

aгардgravierenn,Schnitzerei f

aгарховSchnitzerm,Graveur m,дечигагархоHolzschnitzerm

1 个答案:

答案 0 :(得分:1)

letters = ['б', 'д', 'в'] # add more letters here
text = "слово б word, слово д word" # you can use your "line" as text
for letter in letters:
    letterToReplace = ' '+letter+' '
    newString = ' N['+letter+'] '
    text = text.replace(letterToReplace , newString )
print text
>> слово N[б] word, слово N[д] word