简体   繁体   English

如何使用 python 查找和替换 json 文件中的特定字符串

[英]How to find and replace a specific string in a json file with python

With a python program, I saved a ics file to a json one.The json file contains calendar info.使用 python 程序,我将 ics 文件保存到 json 中。json 文件包含日历信息。 My purpose is to replace a few specific strings (hours) by different ones (Keywords).我的目的是用不同的字符串(关键字)替换一些特定的字符串(小时)。 basically 8:00 to Meeting1;基本上是8:00到Meeting1; 9:00 to Meeting 2 and so on. 9:00 到会议 2,以此类推。 The Json content looks something like this 11/18/21 09:00 UTC-12/19/25 09:45 UTC Meeting-boss: - None . Json 内容看起来像这样11/18/21 09:00 UTC-12/19/25 09:45 UTC Meeting-boss: - None This being done by a python program would probably be to painful to change so I have to work with that.这是由 python 程序完成的,更改可能会很痛苦,所以我必须解决这个问题。 This is the python program that parses the ics file into a json one:这是将 ics 文件解析为 json 的 python 程序:


from datetime import datetime, timedelta, timezone
import icalendar
from dateutil.rrule import *
f = open('myschool.json', 'w')

def parse_recurrences(recur_rule, start, exclusions):
    """ Find all reoccuring events """
    rules = rruleset()
    first_rule = rrulestr(recur_rule, dtstart=start)
    rules.rrule(first_rule)
    if not isinstance(exclusions, list):
        exclusions = [exclusions]
        for xdate in exclusions:
            try:
                rules.exdate(xdate.dts[0].dt)
            except AttributeError:
                pass
    now = datetime.now(timezone.utc)
    this_year = now + timedelta(days=60)
    dates = []
    for rule in rules.between(now, this_year):
        dates.append(rule.strftime("%D %H:%M UTC "))
    return dates

icalfile = open('myschool.ics', 'rb')
gcal = icalendar.Calendar.from_ical(icalfile.read())
for component in gcal.walk():
    if component.name == "VEVENT":
        summary = component.get('summary')
        description = component.get('description')
        location = component.get('location')
        startdt = component.get('dtstart').dt
        enddt = component.get('dtend').dt
        exdate = component.get('exdate')
        if component.get('rrule'):
            reoccur = component.get('rrule').to_ical().decode('utf-8')
            for item in parse_recurrences(reoccur, startdt, exdate):
                print("{0} {1}: {2} - {3}\n".format(item, summary, description, location), file = f)
        else:
            print("{0}-{1} {2}: {3} - {4}\n".format(startdt.strftime("%D %H:%M UTC"), enddt.strftime("%D %H:%M UTC"), summary, description, location), file = f)
icalfile.close()

I have no idea how to this.我不知道该怎么做。 The json could be a txt file if it makes things easier btw. json 可以是一个 txt 文件,如果它使事情变得更容易顺便说一句。 All help appreciated:)所有帮助表示赞赏:)

I think you can use the "re" package (python regular expression) to do it and then you can use the method replace to replace the targeted string with the needed string我认为您可以使用“re” package (python 正则表达式)来执行此操作,然后您可以使用方法 replace 将目标字符串替换为所需的字符串

you can read more about the re module here https://docs.python.org/3/library/re.html您可以在此处阅读有关re 模块的更多信息https://docs.python.org/3/library/re.html

and this site will really help you to search through the JSON file and find the target string https://pythex.org/这个站点将真正帮助您搜索 JSON 文件并找到目标字符串https://pythex.org/

Your code is a bit hard to follow without having an example icalendar component along side the current json output, as well as your intended json output. Your code is a bit hard to follow without having an example icalendar component along side the current json output, as well as your intended json output. If I am interpreting your code correctly, it looks like you are constructing your json by formatting the data retrieved from the icalendar component using component.get().如果我正确解释了您的代码,那么您似乎正在通过使用 component.get() 格式化从 icalendar 组件检索到的数据来构建 json。 If this is correct, you should be able to replace the time portion (8:00 and 9:00 in your example) with "Meeting 1" and "Meeting 2" within the variable that holds this string when you first extract it from the icalendar file.如果这是正确的,当您第一次从日历文件。 You could then assemble your json from the strings as your currently are, since the change you would like to make would have be accomplished before constructing your json file.然后,您可以像当前一样从字符串中组装 json,因为您想要进行的更改将在构建 json 文件之前完成。

For example: if startdt = component.get('dtstart').dt holds the string extracted from icalendar corresponding to "11/18/21 09:00", you would use either regex or something like string splitting to remove "09:00" and add "Meeting 2".例如:如果 startdt = component.get('dtstart').dt 包含从 icalendar 中提取的对应于“11/18/21 09:00”的字符串,则可以使用正则表达式或字符串拆分之类的方法来删除“09: 00”并添加“会议 2”。 Once the variable startdt is modified to have the data you want, your json should then inherit these changes.一旦变量 startdt 被修改为您想要的数据,您的 json 应该继承这些更改。

assuming startdt holds the string which supplies date and time to your json (EX: "11/18/21 09:00") you could use the following code to change the string to "11/18/21 Meeting 2".假设 startdt 包含为您的 json 提供日期和时间的字符串(例如:“11/18/21 09:00”),您可以使用以下代码将字符串更改为“21 年 11 月 18 日会议 2”。

# import regex library
import re

# takes place of startdt = component.get('dtstart').dt in your code to make example easier.
startdt = "11/18/21 09:00"

# uses regex patter that looks for 2 digits, then ":" followed by 2 digits,
#then replaces the string that matches that pattern with "Meeting 2"
startdt = startdt.replace(re.search('\d{2}:\d{2}', startdt)[0], "Meeting 2")

print(startdt)

You don't specify how you decide how to name each meeting during the replacement, but you can just pass whatever name you want to the startdt.replace() line, rather than the hardcoded "Meeting 2" in the example.您没有指定如何在替换期间决定如何命名每个会议,但您可以将任何您想要的名称传递给 startdt.replace() 行,而不是示例中的硬编码“会议 2”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM