1.需求
在网上搜到了一篇英文小说,是一句英语一句中文翻译的形式,我想改成,前部分是英语,后半分是中文翻译。
修改完的结构:
2.代码实现
python代码:
def split_chinese(strings):
for _char in strings:
if '\u4e00' <= _char <= '\u9fa5':
return _char
english_sentence = ""
chinese_sentence = ""
i = 0
with open('./input.txt', mode="r", encoding="utf-8") as file:
for line in file:
_char = split_chinese(line)
index = line.find(_char)
print("英文: ", line[: index])
i = i + 1
english_sentence += str(i) + ". " + line[: index] + "\n"+ "\n"
print("中文: ", line[index:])
chinese_sentence += str( i ) + ". " + line[index:] + "\n"
with open('./english.txt', mode="w", encoding="utf-8") as file:
file.write(english_sentence)
with open('./chinese.txt', mode="w", encoding="utf-8") as file:
file.write(chinese_sentence)
# ./input.txt:输入的原始文档;chinese.txt:输出的中文翻译;english.txt':输出的英文
3.注意
- 在使用代码前,输入的文档格式必须是:一部分英文紧接一部分翻译,中间不能有“回车”。
- 一段英语中不能多加回车。
- 中文后面不能再紧跟英语,否则不能识别出汉语后面的英文。
本文中英文小说是《黎明踏浪号》。