这里我想把关于对各类型文件的读取方法以及对其中数据的操作,只要是我遇到的就纪录下来
一.读取
通常我会以open函数开头,以读取txt文件为例:
data = [] # I will store the data in this list.
with open(file, mode='r') as f:
for line in f:
line = line.replace(old='\t', new='')
data.append(line.strip().split())
f.close()
这是一个比较典型的例子。用open函数将文件打开,然后用 for line in f 读取文件中的每一行数据,然后我再对这每一行的数据进行操作,我这里假设每一行数据之间相差'\t'的距离,我把这些值之间的距离丢掉了,然后对新的这一行数据进行分割并包装成列表。
这里需要灵活运用对字符串的操作 replace, strip和split.
str.replace()
str.replace(old, new[, max])
就是把字符串中old对应字符变成new对应字符,这种替换次数可以用max这个可选参数来设定。例如:
str = "He is too happy to stop laughing which makes his partner feel embarrassed."
不加限制时,
str.replace('is', 'was')
>>'He was too happy to stop laughing which makes hwas partner feel embarrassed.'
max=2 equal to default setting
str.replace('is', 'was', 2)
>>'He was too happy to stop laughing which makes hwas partner feel embarrassed.'
max=1
str.replace('is', 'was', 1)
>>'He was too happy to stop laughing which makes his partner feel embarrassed.'
str.strip()
str.strip(char) 移除首尾中的char,仅限于首尾。默认条件下移除空格或换行符 ,不能对中间的字符进行操作。
参考: https://www.runoob.com/python/att-string-strip.html
str.split()
str.split(str="", num=string.count(str)).
参考: https://www.runoob.com/python/att-string-split.html
讲字符串如何进行切割,以及切割成多少块。
str -- 默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
num -- 分割次数。默认为 -1, 即分隔所有。