首页 / PYTHON / python3 中英文标点转换
python3 中英文标点转换
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python3 中英文标点转换,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1508字,纯文字阅读大概需要3分钟。
内容图文
工作中遇到需要把中文标点转化成英文标点的需求,
#coding=utf-8
import unicodedata
import os
import re
def punctuation_mend(string):
#输入字符串或者txt文件路径
table = {ord(f):ord(t) for f,t in zip(
u',、。!?【】()%#@&1234567890“”‘’',
u',..!?[]()%#@&1234567890""\'\'')} #其他自定义需要修改的符号可以加到这里
if os.path.isfile(string):
with open(string, 'r', encoding='utf-8') as f:
res = unicodedata.normalize('NFKC', f.read())
res = res.translate(table)
with open(string, 'w', encoding='utf-8') as f:
f.write(res)
else:
res = unicodedata.normalize('NFKC', string)
res = res.translate(table)
re.sub(r'(?<=[.,])(?=[^\s])', r' ', res)
return res
def add_space(string):
if os.path.isfile(string):
with open(string, 'r', encoding='utf-8') as f:
line = f.readline()
tmp_f = open(tmp_file, 'w+', encoding='utf-8')
while line:
'''
(?<=[.,]) positive lookbehind that looks for dots or commas
(?=[^\s]) positive lookahead that matches anything that isn't a space
'''
line_new = re.sub(r'(?<=[:.,])(?=[^\s])', r' ', line)
# write line except empty lines with or without space
if not (re.match(r'^\s*$', line_new)):
tmp_f.write(line_new)
line = f.readline()
tmp_f.close()
os.rename(tmp_file, string);
else:
re.sub(r'(?<=[.,])(?=[^\s])', r' ', string)
return string
#print(punctuation_mend('【】()%#@&“”'))
convert_file='~/xxx.txt'
tmp_file='~/tmp.txt'
if __name__ == '__main__':
punctuation_mend(convert_file)
add_space(convert_file)
以上就能转化常用的中文标点, 并且在 逗号, 点号和冒号
后加空格, 再去掉文件中带或者不带空格的空行.
内容总结
以上是互联网集市为您收集整理的python3 中英文标点转换全部内容,希望文章能够帮你解决python3 中英文标点转换所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。