【问题标题】:Replacing certain parts of Array in different folders via Pythion通过 Python 替换不同文件夹中 Array 的某些部分
【发布时间】:2020-05-25 12:19:21
【问题描述】:

我的代码替换了整个文件。而我只想要某些替代品。

下面是我要替换的文件。我只想更改“sheetname”中的一些单词:“Main”

 [  
  {
   "sheetname": "Main",
   "emp_details": [
        [
            "スバム",
            "ksing.shubh@gmail.com",
            "marble",
            "intern"
        ],
        [
            "Gaurav",
            "gaurav.singh@cobol.in",
            "snacks",
            "デボロッパ"
        ],
        [
            "ニキル",
            "nikhil@geeksforgeeks.org",
            "tennis",
            "Full Time"
        ]
       ]
     },
     {
    "sheetname": "Next",
    "emp_details": [
            [
                "スバム",
                "ksing.shubh@gmail.com",
                "fabrics",
                "intern"
            ],
            [
                "Gaurav",
                "gaurav.singh@cobol.in",
                "xenom",
                "デボロッパ"
            ],
            [
                "ニキル",
                "nikhil@geeksforgeeks.org",
                "hiltop",
                "Full Time"
            ]
          ]
         }
        ,{
        "sheetname": "Last",
        "emp_details": [
                [
                    "スバム",
                    "ksing.shubh@gmail.com",
                    "trend",
                    "intern"
                ],
                [
                    "Gaurav",
                    "gaurav.singh@cobol.in",
                    "souvenir",
                    "デボロッパ"
                ],
                [
                    "ニキル",
                    "nikhil@geeksforgeeks.org",
                    "urban",
                    "Full Time"
                ]
            ]
        }
 ]

我要做的是替换“Main”“sheet”中的某些单词,即 sheetname = Main;

提前致谢。任何帮助都会很棒!

下面是我的代码:

import os, re

directory = os.listdir('/Users/Unicorn/Desktop/for all/change')
os.chdir('/Users/Unicorn/Desktop/for all/change')

for file in directory:
    open_file = open(file,'r', encoding='utf-8')
    read_file = open_file.read()
    # changing value
    regex = re.compile('Gaurav')
    # change value
    read_file = regex.sub('Singh', read_file)
    write_file = open(file,'w', encoding='utf-8')
    write_file.write(read_file)

【问题讨论】:

  • 需要替换哪些数据?
  • 例如“主要”的 Gaurav 到 Singh。
  • 你的意思是“sheetname”中的“Gaurav”:“Main”变成“Singh”?
  • 是的,它应该只在“sheetname”中更改:“Main”。
  • 嗨,只使用粗体或标题有点像大喊大叫。为标题使用# 以更好地显示帖子的结构很好,但在所有帖子中始终使用它们可能被视为不礼貌。无需在此处修复,但请不要在下一篇文章中进行。

标签: python arrays json python-3.x python-2.7


【解决方案1】:

将文件中的数据命名为data

 data = [  
  {
   "sheetname": "Main",
   "emp_details": [
        [
            "スバム",
            "ksing.shubh@gmail.com",
            "marble",
            "intern"
        ],
        [
            "Gaurav",
            "gaurav.singh@cobol.in",
            "snacks",
            "デボロッパ"
        ],
        [
            "ニキル",
            "nikhil@geeksforgeeks.org",
            "tennis",
            "Full Time"
        ]
       ]
     },
     {
    "sheetname": "Next",
    "emp_details": [
            [
                "スバム",
                "ksing.shubh@gmail.com",
                "fabrics",
                "intern"
            ],
            [
                "Gaurav",
                "gaurav.singh@cobol.in",
                "xenom",
                "デボロッパ"
            ],
            [
                "ニキル",
                "nikhil@geeksforgeeks.org",
                "hiltop",
                "Full Time"
            ]
          ]
         }
        ,{
        "sheetname": "Last",
        "emp_details": [
                [
                    "スバム",
                    "ksing.shubh@gmail.com",
                    "trend",
                    "intern"
                ],
                [
                    "Gaurav",
                    "gaurav.singh@cobol.in",
                    "souvenir",
                    "デボロッパ"
                ],
                [
                    "ニキル",
                    "nikhil@geeksforgeeks.org",
                    "urban",
                    "Full Time"
                ]
            ]
        }
 ]

import re

word_to_replace = 'Gaurav'
word_to_assign = 'Singh'

for dictionary in data:
    if dictionary.get('sheetname') == 'Main':
        list_data = dictionary.get('emp_details')
        new_data = []
        for item in list_data:
            if word_to_replace in item:
                new_item = []
                for word in item:
                    if word.lower().find(word_to_replace.lower()) == 0:
                        new_word = re.sub(word_to_replace, word_to_assign, word)
                        if new_word == word:
                            new_word = re.sub(word_to_replace.lower(), word_to_assign.lower(), word)
                        new_item.append(new_word)
                    else:
                        new_item.append(word)
                new_data.append(new_item)
            else:
                new_data.append(item)

        dictionary['emp_details'] = new_data

输出

[{'sheetname': 'Main', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'marble', 'intern'], ['Singh', 'singh.singh@cobol.in', 'snacks', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'tennis', 'Full Time']]}, {'sheetname': 'Next', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'fabrics', 'intern'], ['Gaurav', 'gaurav.singh@cobol.in', 'xenom', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'hiltop', 'Full Time']]}, {'sheetname': 'Last', 'emp_details': [['スバム', 'ksing.shubh@gmail.com', 'trend', 'intern'], ['Gaurav', 'gaurav.singh@cobol.in', 'souvenir', 'デボロッパ'], ['ニキル', 'nikhil@geeksforgeeks.org', 'urban', 'Full Time']]}]

【讨论】:

  • 我不知道为什么,但代码不起作用。不过感谢您的帮助。
  • @Rubin 你有错误吗?我已经在您列出的数据上对此进行了测试。 data需要按字典列表。
  • 能否请您添加完整的代码,可能是因为我在某个地方弄错了。打扰了!
  • @Rubin 将字典分配列表添加到变量data
  • 我做了这样的事情。 import json word_to_replace = 'Gaurav' new_word = 'Singh' with open('new.json', 'r',encoding='utf-8') as file: data = json.load(file) for dictionary in data: if dictionary.get('sheetname') == 'Main': ........(复制代码)............ dictionary['emp_details'] = new_data with open('wow.json', 'w',encoding='utf-8') as file: json.dump(data, file, indent=4) 问题是日文字符变成 /u... 像那个。
【解决方案2】:

这是一个json数据,如果你把它保存在一个文件中,它可以用json模块加载并简单地迭代然后添加你的条件

import json
import os
import sys

directory = os.listdir('/Users/Unicorn/Desktop/for all/change')
os.chdir('/Users/Unicorn/Desktop/for all/change')

for file in directory:
    open_file = open(file,'r', encoding='utf-8')
    read_file = open_file.read()
    open_file.close()
    # loads json file so it can be treated just like dictionary/list object in python
    data_json = json.loads(read_file)

    # iterate sheet item in data
    for sheet in data_json:
        # this is where you put your condition for sheetname == "Main"
        if sheet['sheetname'] == 'Main':
            # iterate over emp_detail because it is a list
            for emp_detail in sheet['emp_details']:
                # this is my simple method to replace item on a list
                if 'Gaurav' in emp_detail:
                    emp_detail[emp_detail.index('Gaurav')] = 'Singh'
    data_final = json.dumps(data_json)
    open_file = open(file,'w', encoding='utf-8')
    open_file.write(data_final)
    open_file.close()

【讨论】:

  • 实际上它正在工作并且不工作。我的意思是它非常适合这种情况,但是日文字符变成了某种 unicode。而且我还想获​​得输出文件的设计。不过非常感谢。
猜你喜欢
  • 2023-01-03
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 2021-05-08
  • 2020-01-27
  • 2021-03-04
  • 2018-07-14
相关资源
最近更新 更多