Python实现对csv文件的字典读写(pandas、csv和直接文件读写3种方法)

1、CSV文件

在这里插入图片描述
在这里插入图片描述

2、代码实现

2.1 pandas和csv方法读写

import pandas as pd
import csv
import os.path

# 代码背景:word_list 内元素是key,species_code_list 内元素是value,需要保存csv格式文件
word_list = pd.Series(
    ['main', 'int', 'char', 'if', 'else', 'for', 'while', 'return', 'void', 'STRING', 'ID', 'INT', '=', '+',
     '-', '*', '/', '(', ')', '[', ']', '{', '}', ',', ':', ';', '>', '<', '>=', '<=', '==', '!='])
species_code_list = pd.Series(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
     36, 37, 38, 29, 40])
system_table = dict(zip(word_list, species_code_list))
labels = ['单词符号', '种别码']


def writeToCSVBYPandas(fileName) -> '保存字典类型到csv格式文件':
    df = pd.concat([word_list, species_code_list], axis=1)
    # 或    df = pd.DataFrame(list(system_table.items()))
    # DataFrame存储为csv格式文件,index表示是否显示行名,默认是
    df.to_csv(fileName, header=labels, sep=',', index=False, encoding="utf_8_sig")


def readFromCSVByPandas(fileName) -> '返回字典类型':
    df = pd.read_csv(fileName, sep=',', encoding="utf_8_sig")
    dict_tmp = dict(zip(df.values[:, 0], df.values[:, 1]))
    for item in dict_tmp.items():
        print(item)
    return dict_tmp


def writeToCSVByCsv(fileName) -> '保存字典类型到csv格式文件':
    df = pd.concat([word_list, species_code_list], axis=1)
    out = open(fileName, 'w', newline='', encoding="utf_8_sig")
    # 设定写入模式
    writer = csv.DictWriter(out, fieldnames=tuple(labels))
    writer.writeheader()
    for row in range(df.shape[0]):
        dict_tmp = {labels[0]: df.values[row, 0], labels[1]: df.values[row, 1]}
        writer.writerow(dict_tmp)
    out.close()


def readFromCSVByCsv(fileName) -> '返回字典类型':
    dict1 = {}
    if not os.path.isfile(fileName):
        print("File does not exist!")
        return dict1
    try:
        file = open(fileName, encoding="utf_8_sig")
        reader = csv.DictReader(file, fieldnames=tuple(labels))
        i = 1
        for dict_tmp in reader:
            if i == 1:  # 除去顶部
                i = 0
                continue
            list_tmp = list(dict_tmp.values())
            dict1[list_tmp[0]] = list_tmp[1]
        file.close()
        for item in dict1.items():
            print(item)
    except Exception as e:
        print(str(e))
    finally:
        return dict1


if __name__ == '__main__':
    fileName = r'./2.csv'
    readFromCSVByPandas(fileName)
    readFromCSVByCsv(fileName)

2、直接读写

import pandas as pd

# 代码背景:word_list 内元素是key,species_code_list 内元素是value,需要保存csv格式文件
word_list = pd.Series(
    ['main', 'int', 'char', 'if', 'else', 'for', 'while', 'return', 'void', 'STRING', 'ID', 'INT', '=', '+',
     '-', '*', '/', '(', ')', '[', ']', '{', '}', ',', ':', ';', '>', '<', '>=', '<=', '==', '!='])
species_code_list = pd.Series(
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 10, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
     36, 37, 38, 29, 40])
system_table = dict(zip(word_list, species_code_list))


def readFromCsv(fileName):
    fo = open(fileName)
    ls = []
    for line in fo:
        line = line.replace('\n', '')
        ls.append(line.split(','))
    fo.close()
    return ls


def writeToCsv(fileName, lst, fieldnames=None):
    f = open(fileName, 'w')
    if fieldnames is not None:
        item = [str(i) for i in fieldnames]
        f.write(','.join(item)+"\n")
    for item in lst.copy():
        item = [str(i) for i in item]
        f.write(','.join(item)+"\n")
    f.close()


def main():
    fileName = r'./2.csv'
    lst = [list(item) for item in system_table.items()]
    labels = ['单词符号', '种别码']
    writeToCsv(fileName, lst, labels)
    ls = readFromCsv(fileName)
    for item in ls:
        print(item)


if __name__ == '__main__':
    main()

在这里插入图片描述

### 回答1: 可以使用Pythoncsv模块来实现,代码示例如下:import csv# 读取csv csv_file = csv.reader(open('your_file.csv', 'r'))# 定义字典 d = {'key1':'value1', 'key2':'value2'}# 将csv的每一行逐个读取出来 for line in csv_file: # 对每一行中的每个元素进行判断,如果元素在字典中,则替换成相应的值 for i in range(len(line)): if line[i] in d: line[i] = d[line[i]]# 写入新的csv文件 csv_write = csv.writer(open('your_file.csv', 'w')) csv_write.writerows(csv_file) ### 回答2: 使用PythonCSV文件利用字典中的关键字进行替换的方法如下: 1. 首先,导入csv模块和pandas模块,分别用于读取和写入CSV文件和处理数据。 2. 创建一个字典,将需要替换的关键字作为字典的键,将替换后的值作为字典的值。 3. 使用pandas的read_csv函数读取CSV文件,并将数据保存在一个DataFrame对象中。 4. 使用DataFrame对象的replace函数将字典中的关键字替换为对应的值。 5. 使用pandas的to_csv函数将替换后的数据写入新的CSV文件中。 下面是示例代码: ```python import csv import pandas as pd # 创建字典,将需要替换的关键字作为键,将替换后的值作为值 replace_dict = { '关键字1': '替换值1', '关键字2': '替换值2', '关键字3': '替换值3' } # 使用pandas的read_csv函数读取CSV文件,并保存在DataFrame对象中 df = pd.read_csv('input.csv') # 使用DataFrame对象的replace函数将关键字替换为对应的值 df.replace(replace_dict, inplace=True) # 使用pandas的to_csv函数将替换后的数据写入新的CSV文件中 df.to_csv('output.csv', index=False) ``` 以上代码中,`input.csv`为输入的CSV文件,`output.csv`为输出的替换后的CSV文件,可以根据实际需要进行修改。注意,代码中的关键字替换是按照完全匹配进行的,如果需要进行部分匹配或大小写不敏感的替换,可以使用正则表达式或其他方法进行处理。 ### 回答3: 使用PythonCSV文件利用字典中的关键字进行替换可以通过csv模块和字典的键值对进行操作。下面是代码示例: ```python import csv # 定义替换规则的字典 replace_dict = { "关键字1": "替换值1", "关键字2": "替换值2", # 添加更多的替换规则 } # 读取CSV文件 with open('input.csv', 'r') as file: reader = csv.DictReader(file) # 创建输出CSV文件 with open('output.csv', 'w', newline='') as output_file: writer = csv.DictWriter(output_file, fieldnames=reader.fieldnames) writer.writeheader() # 替换关键字并写入新的CSV文件中 for row in reader: updated_row = {} for fieldname, value in row.items(): if value in replace_dict: updated_row[fieldname] = replace_dict[value] else: updated_row[fieldname] = value writer.writerow(updated_row) ``` 在示例中,使用了`csv`模块进行CSV文件读写操作。首先定义了一个`replace_dict`字典,存储需要替换的关键字及其对应的替换值。然后使用`with open`语句打开输入CSV文件和输出CSV文件。`csv.DictReader`用于读取输入CSV文件,并使用`csv.DictWriter`创建输出CSV文件,并通过`fieldnames`参数指定输出的列名与输入文件一致。 接下来,使用嵌套的`for`循环遍历输入文件的每一行和每个字段的值。如果字段的值在`replace_dict`中存在对应的键,即关键字,那么将字段的值替换为对应的替换值;否则保持不变。 最后,使用`writer.writerow`方法将更新后的行写入输出CSV文件中。完成后,输入CSV文件中的关键字将被替换为对应的值,并保存在输出CSV文件中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值