1. 用到知识:

1.1Python 文件读写查找、替换的相关操作,

参考:https://blog.csdn.net/liangrui1988/article/details/49539137

1.2Python 插入内容到指定文件的位置

if pos != -1:  
        content = content[:pos] + content_add + content[pos:]

参考:https://blog.csdn.net/jusulysunbeamy/article/details/51290129

1.3Python 的正则表达

Findall

注意:返回的是匹配的字符串,若没有匹配,返回[],而不是什么也不返回

1.4 Python replace的应用

参考:http://www.runoob.com/python/python-reg-expressions.html

1.5 Python 两个list 组合成字典

keys = ['a', 'b', 'c']values = [1, 2, 3]dictionary = dict(zip(keys, values))print(dictionary)

1.6 根据字典的对应关系,对文本进行替换

a_dict = {'apple':'1','tree':'2','123456':'3'}
input_file = open(r'd:\test_body.txt',"r").read();
for key,value in  a_dict.items():input_file=input_file.replace(key,value);

1.7 seek的用法:

seek()方法: 用它设置当前文件读/写指针的偏移。

seek()方法的语法如下:fileObject.seek(offset[, whence])。offset参数指明偏移量,第二个参数指出第一个参数偏移基准是哪里:

offset的取值可为:0,1,2;  0 表示移动到一个绝对位置 (从文件开始算起),1 表示移到一个相对位置 (从当前位置算起), 2 表示对于文件尾的一个相对位置。”

参考:https://blog.csdn.net/liuchunming033/article/details/39376147

1.8 整体代码:

import re
import os
class myMethod(object):def __init__(self, file1):self.file1 = file1self._count = Nonedef count_main(self, main_str):'''搜索文件中指定字符串的个数:param file_name: 文件名称  type=str:param main_str: 要搜索的目标字段  type=str:return:'''fo = open(self.file1, "r+") # 打开文件,r+:打开一个文件用于读写。文件指针将会放在文件的开头。# 参考:http://www.runoob.com/python3/python3-inputoutput.htmlli_list = []fo.seek(0, 0) for s in fo.readlines():li = re.findall(main_str, s)if li != []:li_list.append(li)else:continuefo.close()return len(li_list)def add_str(self, file2, main_str):''':param file_name: 原始的文件名  type = str:param file_new_name: 新生成的文件名 type = str:param main_str: 搜索的字符串:return:'''self._count = self.count_main(main_str)fo = open(self.file1, "r+")fo.seek(0, 0)content = fo.read()for i in range(1, self._count // 3 + 1):add_list = [' id="apname' + str(i) + '" class="ap"', ' class="outer"', ' class="wifi"']for j in range(3):pos = content.find("<g>")if pos != -1:content = content[:pos + 2] + add_list[j] + content[pos + 2:]fo_new = open(file2, "w") # w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被         # 删除。如果该文件不存在,创建新文件。fo_new.write(content)fo_new.close()fo.close()return file2def excelColToList1(excel_file):# data = xlrd.open_workbook(path + '/' + file_r)data = xlrd.open_workbook(excel_file)sheet1 = data.sheets()[0]nrows = sheet1.nrowsncols = sheet1.ncolsapnames = []apInPictureNums= []for i in range(2, nrows):apname = sheet1.cell(i, 9).valueapname = apname.strip()apnames.append(apname)apInPictureNum = sheet1.cell(i, 15).valueapInPictureNum = apInPictureNum.strip()apInPictureNums.append(apInPictureNum)new_str = [apnames[i] + '" name="' + apInPictureNums[i] for i in range(len(apnames))]dictionary = dict(zip(apInPictureNums, new_str))return dictionarydef replace_str(self, file2, old_str, new_str, new_list_strs):''':param file2: 需要替换某些字符串的文本 type=“str”:param old_str: 需要被替换的字符串 type = "str" 比如apname:param new_str: 将old_str 替换成new_str tupe='str' 比如 h2-1f-ap:param new_list_strs: 在AI打点时 的顺序:return:'''fo = open(file2, "r")mykeys = []myvalues = []for i in range(0, self._count // 3):mykeys.append(old_str+str(i+1))myvalues.append(new_str+str(new_list_strs[i]))mydict = dict(zip(mykeys, myvalues))content = fo.read()for key, value in mydict.items():content = content.replace(key, value)fo_new = open(self.file1, "w")fo_new.write(content)fo_new.close()fo.close()os.remove(file2)return self.file1file1 = "testCopy.txt"
file2 = "testCopy2.txt"
main_str = "<g>"
mytest = myMethod(file1)
file = mytest.add_str(file2, main_str)
old_str = "apname"
new_str = "h2-1f-ap"
new_list_strs = [1,2,3]
mytest.replace_str(file, old_str, new_str, new_list_strs)

python 处理文本(.txt文件)相关推荐

  1. python读取所有txt文件_python如何批量读取txt文件

    python批量读取txt文件的方法:首先导入系统模块:然后将文件夹路径更改为需要批量读取的txt文件存放的路径:再调用系统模块得到该文件夹下的所有文件名称:最后遍历文件夹,读取txt文件. 如果文件 ...

  2. python怎么读取txt文件内容然后保存到excel-Python实现读取txt文件并转换为excel的方法示例...

    本文实例讲述了Python实现读取txt文件并转换为excel的方法.分享给大家供大家参考,具体如下: 这里的txt文件内容格式为: 892天平天国定都在?A开封B南京C北京(B) Python代码如 ...

  3. python读取txt文件代码-python批量处理txt文件的实例代码

    通过python对多个txt文件进行处理 读取路径,读取文件 获取文件名,路径名 对响应的文件夹名字进行排序 对txt文件内部的数据相应的某一列/某一行进行均值处理 写入到事先准备好的Excel文件中 ...

  4. python导入txt文件并绘图-Python实现读取txt文件中的数据并绘制出图形操作示例

    本文实例讲述了Python实现读取txt文件中的数据并绘制出图形操作.分享给大家供大家参考,具体如下: 下面的是某一文本文件中的数据. 6.1101,17.592 5.5277,9.1302 8.51 ...

  5. python读取整个txt文件-python怎么读取txt文件内容

    读取文件: 步骤:打开 -- 读取 -- 关闭>>> f = open('/tmp/test.txt') >>> f.read() 'hello python! h ...

  6. python导入txt文件并绘图-Python实现读取txt文件并画三维图简单代码示例

    记忆力差的孩子得勤做笔记! 刚接触python,最近又需要画一个三维图,然后就找了一大堆资料,看的人头昏脑胀的,今天终于解决了!好了,废话不多说,直接上代码! #由三个一维坐标画三维散点 #codin ...

  7. python读取txt文件代码-Python实现读取txt文件并画三维图简单代码示例

    记忆力差的孩子得勤做笔记! 刚接触python,最近又需要画一个三维图,然后就找了一大堆资料,看的人头昏脑胀的,今天终于解决了!好了,废话不多说,直接上代码! #由三个一维坐标画三维散点 #codin ...

  8. 怎么退出python命令行cd找到txt文档_《python怎么读取txt文件》

    python怎么创建一个txt文件 python怎么创建txt文件的方法. 如下参考: 1.首用内置的空闲编辑器编辑(单击并选择copy),如下图所示. 2.您可以下载记事本和其他编辑软件,以支持多种 ...

  9. python怎么读取txt文件-python怎么读取txt文件内容

    读取文件: 步骤:打开 -- 读取 -- 关闭>>> f = open('/tmp/test.txt') >>> f.read() 'hello python! h ...

  10. 【Python】读取 txt 文件

    使用 python 脚本对 txt 文件进行读取: 本例中,txt 内容为 1,1,1: with open('./task.txt') as f:lst = f.read() # 使用 with 方 ...

最新文章

  1. 北京智源大会 | AI + 医疗的下一个十年:从公共卫生预警到人类基因密码破解...
  2. 【实习内推】2020腾讯产品暑期实习招聘
  3. twitter数据分析_Twitter上最受欢迎的数据科学文章主题
  4. JMS学习六(ActiveMQ消息传送模型)
  5. Mysql orangepi_orangepi4安装gogs
  6. java判断字符串是否包含某个字符串_Bash技巧:使用[[命令的 =~ 操作符判断字符串的包含关系...
  7. 安卓自动滑屏脚本_【按键精灵】开发抖音全自动养号脚本!可实现自动滑屏
  8. 写给新入职的毕业生们(二)
  9. 线程的常用方法(1)
  10. __line__ php,hitcon 2018受虐笔记一:one-line-php-challenge 学习
  11. Github 教程 -- 使用指南
  12. 前端学习-案例:制作一个超简单的静态页面
  13. 霜降多胃病 三道养胃菜请收好
  14. 紫书——Repeating Decimals UVA - 202
  15. 超强干货:企业数据防泄密的26种实用方法
  16. HttpClient4.5.6设置代理以及代理验证(用户名和密码)
  17. 京东回应显卡售后传闻;​IBM发布第一个2纳米芯片;苹果以工程师数量评估收购对象 | EA周报...
  18. linux虚拟光驱路径,linux虚拟光驱怎么用?
  19. 麦克风波束成形基本原理
  20. NS2 队列管理机制

热门文章

  1. 顶会CIKM‘21论文解读:基于图神经网络的人类行为轨迹恢复模型
  2. 01_国家卫生部PACS相关标准
  3. 国防科技大学计算机学院微电子,国防科大微电子所在声表面波高频特性研究方面取得重要进展...
  4. 状态转移矩阵(status transition matrix )
  5. 没事的时候一个人静静的想着往事
  6. 易推宝网络推广效果怎么样?
  7. idea中使用git创建分支与标签
  8. “博客无双”第二期拍卖活动将于2011年1月26日14:00开始
  9. Android 系统语言切换监听和设置
  10. 《云计算架构技术与实践》拆书12讲!