最近心血来潮要背单词,但是因为是寒假回家忘记带单词本,自己在网上找了一个单词word,但是苦于没有单词朗读。一顿操作发现手机上的软件“不背单词”可以自定义词库,还有跟读功能。但字库的输入体验不好,格式要求txt,每个单词还要回车换行,1000多单词确实操作起来确实麻烦。
现有文件的格式:txt
分析可知需要提取回车之后、‘/’之前的内容
具体流程:
- 读取txt文件转化成可操作类型按照规则提取生成txt
import numpy as np
import os
file_path = ("D:桌面word_my.txt")##file_path为路径
with open(file_path, 'r',encoding='utf-8') as f:#用UTF_8编码打路径文件,否则出现错误UnicodeDecodeErrorbyte 0xad in position
file = f.read();#以str类型读取
print(type(file))#打印file的类型
find_flag=0;
ans=''
sum_of_str=file.count('');#统计字符个数,‘’为空字符,即任意字符都计数
print('字符个数总计:',sum_of_str);
for i in range(0,sum_of_str-1,1):
if find_flag==0:
if file[i] == 'n':
start = i;
find_flag = 1;
else:
if file[i] == '/':
end=i
while file[end-1]==' ':
end=end-1;
#print (file[start:end])
ans=ans+file[start:end]
find_flag = 0;
##生成方法一:直接复制
# print(ans)
##生成方法二:生成新的txt文件
fname=input('fname>')#输入文件名字
print('file' name is:',fname)
fobj=open(fname,'w',encoding='utf-8')
fobj.write(ans)
fobj.close()
# print(file)
输入文件名字 ‘w4’
参考:
Python 字符串 | 菜鸟教程Python 字符串 字符串是 Python 中最常用的数据类型。我们可以使用引号('或')来创建字符串。 创建字符串很简单,只要为变量分配一个值即可。例如: var1 = 'Hello World!' var2 = 'Python Runoob' Python 访问字符串中的值 Python 不支持单字符类型,单字符在 Python 中也是作为一个字符串使用。 Pyt..https://www.runoob.com/python/python-strings.html



