找出文本中含有特定拼音的汉字序列

文本预处理

with open('C:/Users/tellw/Desktop/假面山庄杀人事件.txt',encoding='utf8') as f:
	contents=f.read()

contents=''.join(contents.split('\n'))

import re
import sys

contents=re.sub(r'[0-9a-zA-Z]|\W','',contents)
print(contents)

只保留文本中的汉字

繁简转换

# import zhconv

# r=zhconv.convert(str,'zh-hans')

如果文本中有繁体中文,转换为简体

获取汉字的拼音

from pypinyin import pinyin,Style

r1=pinyin(contents,style=Style.TONE3,neutral_tone_with_five=True)

print(r1)
print(len(contents),len(r1))

调试转录的拼音对汉字的对齐错误

# count=0

# for i,s in enumerate(contents):
# 	r2=pinyin(s,style=Style.TONE3,neutral_tone_with_five=True)
# 	if r2[0][0][:-1]!=r1[i][0][:-1]:
# 		print(contents[i-5:i+6],r1[i],r2[0])
		# count+=1
		# if count==10:
		# 	sys.exit(1)

因为之前预处理的时候主要是排除简单符号,与汉字在同一符号表示区间的符号没有被剔除,造成得到的拼音序列与源汉字文本的不对照,这里需要揪出漏网之鱼,纠正对照关系

输出结果

nstr=''
cset=set()
for i,s in enumerate(contents):
	if r1[i] in [['zui4'],['jin4'],['yi4'],['zhi2'],['you3'],['ge4'],['bu4'],['da4'],['xiao3'],['de5'],['kun4'],['huo4']]:
		nstr+=s
	else:
		cset.add(nstr)
		nstr=''
print(cset)
cset_l=list(cset)
cset_l.sort(key=lambda x:len(x),reverse=True)
print(cset_l)

23.09.20.11.18

posted @ 2025-01-19 19:13  园糯  阅读(71)  评论(0)    收藏  举报