通过python做一个项目。用python来实现电影特征对电影票房的影响
不知道你这个问题是否已经解决, 如果还没有解决的话:常见的数据文件类型如下:
txt
csv
excel(xls\xlsx)
在线网页数据
pdf\word
其他数据软件格式
1 txt文件
更多参考:
https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files文件读取
# 文件input
file_txt = os.path.join(workdir,'Data/demo_text.txt')
# 打开文件
f = open(file_txt, encoding='utf-8')
# 将每行的文本读取,并存为列表
# 此处使用.rstrip()去除空格、换行符
lines_raw = [x.rstrip() for x in f]
# 或者
# lines_raw = [l.rstrip() for l in f.readlines()]
print(lines_raw)
# 关闭文件
f.close()
输出如下:
[‘010杜甫:佳人’, ‘’, ‘绝代有佳人,幽居在空谷。’, ‘自云良家子,零落依草木。’, ‘关中昔丧乱,兄弟遭杀戮。’, ‘官高何足论,不得收骨肉。’, ‘世情恶衰歇,万事随转烛。’, ‘夫婿轻薄儿,新人美如玉。’, ‘合昏尚知时,鸳鸯不独宿。’, ‘但见新人笑,那闻旧人哭!’, ‘在山泉水清,出山泉水浊。’, ‘侍婢卖珠回,牵萝补茅屋。’, ‘摘花不插发,采柏动盈掬。’, ‘天寒翠袖薄,日暮倚修竹。’]
也可以用pandas来读取
df_txt = pd.read_csv(file_txt, names=['txt'], encoding='utf-8')
df_txt.head()
输出如下:
文件输出
# 文件output
file_out = os.path.join(workdir,'Data/out_text.txt')
f_out = open(file_out, encoding='utf-8',mode = 'w')
f_out.writelines(lines_raw)
f_out.close()
2 csv文件
更多参考:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html#pandas.read_csv
csv文件的读入和写出相对简单,直接调用pandas的函数即可。
# 定义文件路径
file_csv = os.path.join(workdir,'Data/demo_csv.csv')
# pandas.read_csv()函数来读取文件
df_csv = pd.read_csv(file_csv,sep=',',encoding='utf-8')
# dataframe.to_csv()保存csv文件
df_csv.to_csv('out_csv.csv',index=False,encoding='utf-8')
# 查看dataframe前3行
df_csv.head(3)
输出如下:
也可以把csv当做文本文件来读取,不过处理过程稍微复杂点,尤其是字段内的取值中含有分隔符(比如逗号)时,例如上面的name字段。