Python简单文本处理(一)

来源:互联网 发布:linux安装包命令 编辑:程序博客网 时间:2024/06/05 22:49

1、join和split

join用来连接字符串,将列表中的单词连接起来从而生成字符串。

>>> ' '.join(['Monty','Python'])'Monty Python'
>>> ','.join(['Hello','World'])'Hello,World'
split则用于分割字符串

>>> 'Monty Python'.split()['Monty', 'Python']>>> 'Hello,World'.split(',')['Hello', 'World']
2、endswith

>>> li = ['visited','me','looked']>>> for w in li:if w.endswith('ed'):print(w)visitedlooked
3、html文本处理

>>> from urllib.request import urlopen>>> url = "http://www.baidu.com">>> html = urlopen(url).read()>>> html[:80]b'<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" conte'
版本3.0之前则是

>>> from urllib import urlopen

4、python处理RSS(feedparser)

feedparser下载地址http://feedparser.org

5、使用python内置方法open()读取本地文件

>>> f = open('README.txt')>>> raw = f.read()>>> raw[:80]'This is Python version 3.4.1\n============================\n\nCopyright (c) 2001, 2'
使用type()查看类型

>>> type(raw)<class 'str'>
列出当前目录下的文件列表

>>> import os>>> os.listdir('.')
上一目录

>>> os.listdir('..')
6、读取文件内容
>>>f = open('README.txt')>>> for line in f:print(line.strip())
7、从版本3.0开始去掉了raw_input(),改用input()
>>> input('Enter some text: ')Enter some text: abc'abc'
8、find()函数

>>> s = 'Monty Python'>>> s.find('Python')6
9、列表是可变的,字符串是不可变的

>>> li = ['Paul','George','John']>>> li[0] = 'Lennon'>>> li['Lennon', 'George', 'John']
>>> s = 'George'>>> s[0] = 'D'Traceback (most recent call last):  File "<pyshell#68>", line 1, in <module>    s[0] = 'D'TypeError: 'str' object does not support item assignment





0 0
原创粉丝点击