Python基础汇总001_txt文件读写、字典使用等

1.利用python读取文件

(1)Python引入了with语句来自动帮我们调用close()方法

<1>读取指定路径下的文件

with open('/path/to/file', 'r') as f:
    print(f.read())

<2>写文件

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')

(2)Python 按行读取txt文件,并放入列表中(掌握)

每次只读取和显示一行,适用读取大文件

file = open("../aspect_ner_csv_files/aspect_words.txt","r",encoding="utf-8")
word_list=[]
for line in file:
    word_list.append(line.strip())  #将每一行文件加入到word_list列表中
file.close()
print(word_list)

控制台输出:

(3)读取txt文件,删除重复行

#读取文件
total_stopwords = open('stopwords_txt/total_stopwords.txt', 'r',encoding="utf-8")
total_stopwords_after_filter = open('stopwords_txt/total_stopwords_after_filter.txt', 'w',encoding="utf-8")
new = []
#计算变量
count_total_stopwords=0
count_total_after_filter=0
#利用for循环读取每一行
#去重
for line in total_stopwords.readlines():
    count_total_stopwords+=1  #行数+1
    if line not in new:  #去重
        count_total_after_filter+=1
        new.append(line)
        total_stopwords_after_filter.writelines(line)

total_stopwords.close()
total_stopwords_after_filter.close()
print(count_total_stopwords)
print(count_total_after_filter)

控制台输出:

(4)将变量按行写入txt文本中

如果要按行写入,我们只需要再字符串开头或结尾添加换行符' '即可:

f = open('../aspect_ner_csv_files/test_biaozhu_pos.txt', 'a', encoding='utf-8')
f.write('
' + words_bmeso_pos)
f.close()

(5)pandas文件读取数据,写入txt中

从pandas的dataframe中,逐行读取某列的数据,经过分词后,将reviews变量逐行写入

Python open() 函数用于打开一个文件,并返回文件对象,在对文件进行处理过程都需要使用到这个函数,如果该文件无法被打开,会抛出 OSError。

注意:使用 open() 函数一定要保证关闭文件对象,即调用 close() 函数。

open函数的参数列表:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

参数说明:

  • file: 必需,文件路径(相对或者绝对路径)。
  • mode: 可选,文件打开模式
  • buffering: 设置缓冲
  • encoding: 一般使用utf8
  • errors: 报错级别
  • newline: 区分换行符
  • closefd: 传入的file参数类型
模式描述
t 文本模式 (默认)。
x 写模式,新建一个文件,如果该文件已存在则会报错。
b 二进制模式。
+ 打开一个文件进行更新(可读可写)。
U 通用换行模式(不推荐)。
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。
for index,row in df.iterrows():
    reviews=row['reviews']
    review_split, review_pos, review_split_pos=fenci_and_pos(reviews)
    print(review_split)
    print(review_pos)
    print(review_split_pos)
    df.loc[index,'review_split']=review_split
    df.loc[index,'review_pos']=review_pos
    df.loc[index,'review_split_pos']=review_split_pos
    txt_id=1
    review_split_txt_path='split_result_txt/split_txt_'+str(txt_id)+'.txt'
    f = open(review_split_txt_path, 'a',encoding='utf-8')
    f.write('
' + review_split)
    f.close()
    df.to_csv('hotelreviews50_2129.csv', header=None, index=False)  # header=None指不把列号写入csv当中

2.列表生成式 

li = [i ** 2 for i in range(1,11)]
print(li)

输出:

 3.Counter

Counter是一个容器对象,主要的作用是用来统计散列对象

from collections import Counter
lists = ['a', 'a', 'b', 5, 6, 7, 5]
a = Counter(lists)
print(a)  # Counter({'a': 2, 5: 2, 'b': 1, 6: 1, 7: 1})
b=a.most_common(2)  #输出是一个集合 [('a', 2), (5, 2)]
print(b)
c=dict(b) #将集合转化为字典
print(c)
# 将上面的过程合并成一句话,其作用就是统计集合中的各个元素出现的次数,取出出现次数最多放入字典中
d=dict(Counter(lists).most_common(2))
print(d)

效果图:

 4.字典(dict)

(1)items 方法

Python 字典 items() 函数作用:以列表返回可遍历的(键, 值) 元组数组。

dict = {'老大':'15岁',
        '老二':'14岁',
        '老三':'2岁',
        '老四':'在墙上'
        }
print(dict.items())
for key,values in dict.items():
    print(key + '已经' + values + '')

控制台输出:

(2)获取字典的key列表和value列表

# -*- coding: utf-8 -*-
# 定义一个字典
dic = {'剧情': 11, '犯罪': 10, '动作': 8, '爱情': 3, '喜剧': 2, '冒险': 2, '悬疑': 2, '惊悚': 2, '奇幻': 1}
#通过list将字典中的keys和values转化为列表
keys = list(dic.keys())
values = list(dic.values())
# 结果输出
print("keys列表为:",end='')
print(keys)
print("values列表为:",end='')
print(values)

控制台输出:

 5.统计列表中各种值数据出现的频次

(1)利用字典自定义函数实现(必须掌握)

def get_counts(sequence):
    counts = {}
    for x in sequence:
        if x in counts:
            counts[x] += 1
        else:
            counts[x] = 1
    return counts

小案例:

list01=[1,1,2,22,3,3,-2,3,-34,1,1,2,2,2,2,22,-2,-2]
dict01={}
for i in list01:
    if i in dict01:
        dict01[i]+=1
    else:
        dict01[i]=1

#对字典按value降序排列
a = sorted(dict01.items(), key=lambda x: x[1], reverse=True)
print(a)

控制台输出:

(2)dataframe格式的value_counts()

pos_count_series=df['review_pos'].value_counts()  #统计review_pos列中各种值数据出现的频次
print(pos_count_series)
list_pos=pos_count_series.index  #可以将其理解为列表
list_count=pos_count_series.values

控制台输出:

原文地址:https://www.cnblogs.com/luckyplj/p/13132525.html