本帖最后由 vsyour 于 2018-4-8 09:51 编辑
突然小姐姐说: "现在做数据都做的天天烦死".
需求大概如上图.
整理了一下,基本上就是这样的.
1.给一堆文本文档.
2.把这些文本转成每行11个字排版.
这个很基础.但是做起来还是需要考虑不少问题的.
这里分享下代码与大家一起交流下.
[Python] 纯文本查看 复制代码 #coding:utf-8
import os
def getTxtFileName(dir="."):
items = os.listdir(dir)
newlist = []
for names in items:
if names == 'redme.txt' or 'new_' in names:
continue
if names.endswith(".txt"):
newlist.append(names)
return newlist
def openFile(fileName):
with open(fileName,'r') as f:
txtLines = []
for i in f:
txtLines.append(i.strip('\n'))
# i+=i
return ''.join(txtLines)
def outLine(fileName,line):
with open('new_'+fileName,'a+') as f:
f.write(line+'\n')
if __name__ == '__main__':
dir='./'
for fileName in getTxtFileName(dir):
a=0
oneKeyOk=[]
if os.path.exists('new_' + fileName):
# 如果文件已经存在则直接跳过
print('[+]','new_' + fileName+'已经存在,本次不处理!')
continue
print('[+] 开始处理',fileName)
for oneKey in openFile(fileName):
# 去掉了换行的单个字
a +=1
if a <= 11 :
oneKeyOk.append(oneKey)
else:
# print(''.join(oneKeyOk))
outLine(fileName,''.join(oneKeyOk))
oneKeyOk = []
a = 0
if len(oneKeyOk) != 0:
outLine(fileName, ''.join(oneKeyOk))
os.system('pause')
执行效果:
最后用exe打包了一下:
链接: https://pan.baidu.com/s/14O3gSKg4Help5Zp9rIE4Rg 密码: 5tim
感谢13楼的兄弟.
[Asm] 纯文本查看 复制代码 #coding:utf-8
import os
def getTxtFileName(dir="."):
items = os.listdir(dir)
newlist = []
for names in items:
if names == 'redme.txt' or 'new_' in names:
continue
if names.endswith(".txt"):
newlist.append(names)
return newlist
def openFile(fileName):
with open(fileName,'r') as f:
txtLines = []
for i in f:
txtLines.append(i.replace('\n',''))
# i+=i
return ''.join(txtLines)
def outLine(fileName,line):
with open('new_'+fileName,'a+') as f:
f.write(line)
if __name__ == '__main__':
dir='./'
for fileName in getTxtFileName(dir):
a=0
oneKeyOk=[]
if os.path.exists('new_' + fileName):
# 如果文件已经存在则直接跳过
print('[+]','new_' + fileName+'已经存在,本次不处理!')
continue
print('[+] 开始处理',fileName)
j = 1
b = []
text=openFile(fileName)
while True:
i = text[j:(j + 11)] + '\n'
b.append(i)
j += 11
if i == '\n':
break
# print(''.join(b).strip())
outLine(fileName, ''.join(b).strip())
os.system('pause')
|