Ⅰ python删除文件中指定内容
下面代码假定你是要删掉20150723开头的行:
lines=[lforlinopen("file.txt","r")ifl.find("20150723",0,8)!=0]
fd=open("file.txt","w")
fd.writelines(lines)
Python可以利用python-docx模块处理word文档,处理方式是面向对象的。也就是说python-docx模块会把word文档,文档中的段落、文本、字体等都看做对象,对对象进行处理就是对word文档的内容处理。
二,相关概念
如果需要读取word文档中的文字(一般来说,程序也只需要认识word文档中的文字信息),需要先了解python-docx模块的几个概念。
1,Document对象,表示一个word文档。
2,Paragraph对象,表示word文档中的一个段落
3,Paragraph对象的text属性,表示段落中的文本内容。
三,模块的安装和导入
需要注意,python-docx模块安装需要在cmd命令行中输入pip install python-docx,如下图表示安装成功(最后那句英文Successfully installed,成功地安装完成,十分考验英文水平。)
注意在导入模块时,用的是import docx。
也真是奇了怪了,怎么安装和导入模块时,很多都不用一个名字,看来是很有必要出一个python版本的模块管理程序python-maven了,本段纯属PS。
四,读取word文本
在了解了上面的信息之后,就很简单了,下面先创建一个D:\temp\word.docx文件,并在其中输入如下内容。
然后写一段程序,代码及输出结果如下:
#读取docx中的文本代码示例
import docx
#获取文档对象
file=docx.Document("D:\\temp\\word.docx")
print("段落数:"+str(len(file.paragraphs)))#段落数为13,每个回车隔离一段
#输出每一段的内容
for para in file.paragraphs:
print(para.text)
#输出段落编号及段落内容
for i in range(len(file.paragraphs)):
print("第"+str(i)+"段的内容是:"+file.paragraphs[i].text)
运行结果:
================ RESTART: F:/360data/重要数据/桌面/学习笔记/readWord.py ================
段落数:13
啊
我看见一座山
雄伟的大山
真高啊
啊
这座山是!
真的很高!
第0段的内容是:啊
第1段的内容是:
第2段的内容是:我看见一座山
第3段的内容是:
第4段的内容是:雄伟的大山
第5段的内容是:
第6段的内容是:真高啊
第7段的内容是:
第8段的内容是:啊
第9段的内容是:
第10段的内容是:这座山是!
第11段的内容是:
第12段的内容是:真的很高!
>>>
总结
以上就是本文关于Python读取word文本操作详解的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
Ⅲ python中关于图片添加文字
1、在美图秀秀中打开图片,然后选择文字,在静态文字里面粘贴大段文字,点击应用文字后就会自动排版到画面中;2、但是美图秀秀的文字排版不支持自动换行功能,所以需要手动在文本框那里按回车换行。
Ⅳ python sns.pointplot如何添加文本信息
C语言有__LINE__来表示源代码的当前行号,经常在记录日志时使用。Python如何获取源代码的当前行号?
The C Language has the __LINE__ macro, which is wildly used in logging, presenting the current line of the source file. And how to get the current line of a Python source file?
exception输出的函数调用栈就是个典型的应用:
A typical example is the output of function call stack when an exception:
python代码
File "D:\workspace\Python\src\lang\lineno.py", line 19, in <mole>
afunc()
File "D:\workspace\Python\src\lang\lineno.py", line 15, in afunc
errmsg = 1/0
ZeroDivisionError: integer division or molo by zero
那么我们就从错误栈的输出入手,traceback模块中:
Now that, Let's begin with the output of an exception call stack, in the traceback mole:
python代码
def print_stack(f=None, limit=None, file=None):
"""Print a stack trace from its invocation point.
The optional 'f' argument can be used to specify an alternate
stack frame at which to start. The optional 'limit' and 'file'
arguments have the same meaning as for print_exception().
"""
if f is None:
try:
raise ZeroDivisionError
except ZeroDivisionError:
f = sys.exc_info()[2].tb_frame.f_back
print_list(extract_stack(f, limit), file)
def print_list(extracted_list, file=None):
"""Print the list of tuples as returned by extract_tb() or
extract_stack() as a formatted stack trace to the given file."""
if file is None:
file = sys.stderr
for filename, lineno, name, line in extracted_list:
_print(file,
' File "%s", line %d, in %s' % (filename,lineno,name))
if line:
_print(file, ' %s' % line.strip())
traceback模块构造一个ZeroDivisionError,并通过sys模块的exc_info()来获取运行时上下文。我们看到,所有的秘密都在tb_frame中,这是函数调用栈中的一个帧。
traceback constructs an ZeroDivisionError, and then call the exc_info() of the sys mole to get runtime context. There, all the secrets hide in the tb_frame, this is a frame of the function call stack.
对,就是这么简单!只要我们能找到调用栈frame对象即可获取到行号!因此,我们可以用同样的方法来达到目的,我们自定义一个lineno函数:
Yes, It's so easy! If only a frame object we get, we can get the line number! So we can have a similar implemetation to get what we want, defining a function named lineno:
python代码
import sys
def lineno():
frame = None
try:
raise ZeroDivisionError
except ZeroDivisionError:
frame = sys.exc_info()[2].tb_frame.f_back
return frame.f_lineno
def afunc():
# if error
print "I have a problem! And here is at Line: %s"%lineno()
是否有更方便的方法获取到frame对象?当然有!
Is there any other way, perhaps more convinient, to get a frame object? Of course YES!
python代码
def afunc():
# if error
print "I have a proble! And here is at Line: %s"%sys._getframe().f_lineno
类似地,通过frame对象,我们还可以获取到当前文件、当前函数等信息,就像C语音的__FILE__与__FUNCTION__一样。其实现方式,留给你们自己去发现。
Thanks to the frame object, similarly, we can also get current file and current function name, just like the __FILE__ and __FUNCTION__ macros in C. Debug the frame object, you will get the solutions.
Ⅳ 请问python thinter的窗口中如何在输入框中添加一个❌来删除里面的内容呢
你说的是TKinter吧,输入框可以设置默认值,再写个清除默认值的按钮
Ⅵ python删除特定文字下面的所有内容并保存
初学就要多查找相关资料,然后自己尝试写代码,在改错中进步:
思路:
先建立一个临时文件(用open即可),
然后顺序读取txt文件的每一行(open,readline,用 while循环),
判断读取的那一行是否是abcdefg,不是就保存到临时文件,是的话就结束循环。
关闭文件,然后可以把原来的txt文件删除,把临时文件更名为txt。(import os,用os操作)
Ⅶ python 删除一张图片
你是指删除系统上的文件,还是指释放内存中的图片?你用的是PIL?
如果删除系统中的文件,可以用os.remove(targetFile)。
如果是释放内存,好像不需要吧
Ⅷ Python的列表元素添加与删除
去掉for循环中的sandwich_orders.remove(asd)语句
在for asd 中改变了参与循环的sandwich_orders的长度,移除了其中的值 ,导致for asd in sandwich_orders中对sandwich_orders中元素迭代的不可预知性
Ⅸ python 文本编辑 添加,删除,编辑文字
#-*-coding:utf-8-*-
importsys
classFileContent:
lines=[]
def__init__(self):
pass
def_add(self,line):
self.lines.append(line)
def_find(self,linenum,oldstr,newstr):
self.lines[linenum:linenum+1]=[self.lines[linenum].replace(oldstr,newstr)]
def_reaplce(self,linenum,line):
self.lines[linenum:linenum+1]=[line]
def_delete(self,linenum):
delself.line[linenum]
defadd(self,line):
self._add(line)
deffind(self,linenum,oldstr,newstr):
returnself._find(linenum,oldstr,newstr)
defreplace(self,linenum,line):
returnself._reaplce(linenum-1,line)
defdelete(self,linenum):
self._delete(linenum)
defgetlines(self):
returnlen(self.lines)
defclear(self):
self.lines=[]
defsave(self,filename):
withopen(filename,'w')asfw:
forlineinself.lines:
fw.write(line+' ')
deflist(self):
i=1
forlineinself.lines:
print(str(i).ljust(3)+')'+line)
i+=1
classFileEditorInterface:
fc=FileContent()
def__init__(self):
self.help()
self.command()
defhelp(self):
print('=============================')
print('a-add')
print('d-delete')
print('r-replace')
print('f-findandreplace')
print('c-clear')
print('s-save')
print('h-help')
print('q-quit')
defcommand(self):
ch=''
whilech!='q':
self.fc.list()
ch=input('=================================== Commanda,d,r,f,c,s,l,h?:')
ifch=='a':
line=input('>')
whileline!='#':
self.fc.add(line)
line=input('>')
ifch=='d':
linenum=int(input('Deletelineno:'))
iflinenum<=0:
print('number<=0.')
continue
self.fc.delete(linenum)
ifch=='r':
linenum=int(input('Replacelineno:'))
iflinenum<=0:
print('number<=0.')
continue
replstr=input('Replacementline:')
self.fc.replace(linenum,replstr)
ifch=='f':
findstr=input('Findstring:')
replstr=input('Replacewith:')
foriinrange(self.fc.getlines()):
self.fc.find(i,findstr,replstr)
ifch=='c':
self.fc.clear()
ifch=='s':
filename=input('Filename:')
self.fc.save(filename)
ifch=='h':
self.help()
if__name__=="__main__":
app=FileEditorInterface()
Ⅹ python 添加文本内容到文件
执行的python脚本:
#!/usr/local/python
#coding=UTF-8
importos
file=open("test.html","r")
fileadd=open("test.txt","r")
content=file.read()
contentadd=fileadd.read()
file.close()
fileadd.close()
pos=content.find("</table>")
ifpos!=-1:
content=content[:pos]+contentadd+content[pos:]
file=open("test.html","w")
file.write(content)
file.close()
print"OK"