我有一系列主要是英文的文本,但包含一些带有中文字符的短语。这里有两个例子:
s1 = "You say: ??. I say: ??"
s2 = "??, my friend, ????"
Run Code Online (Sandbox Code Playgroud)
我试图找到每个中文块,应用一个函数来翻译文本(我已经有办法进行翻译),然后替换字符串中的翻译文本。所以输出将是这样的:
o1 = "You say: hello. I say: goodbye"
o2 = "The answer, my friend, is blowing in the wind"
Run Code Online (Sandbox Code Playgroud)
通过这样做,我可以轻松找到汉字:
utf_line = s1.decode('utf-8')
re.findall(ur'[\u4e00-\u9fff]+',utf_line)
Run Code Online (Sandbox Code Playgroud)
...但我最终得到了所有汉字的列表,并且无法确定每个短语的开始和结束位置。
小智 6
您始终可以通过re.sub()在 python 中使用就地替换匹配的正则表达式 。
尝试这个:
print(re.sub(r'([\u4e00-\u9fff]+)', translate('\g<0>'), utf_line))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3183 次 |
| 最近记录: |