社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  roadrunner  »  全部回复
回复总数  2
6 年前
回复了 roadrunner 创建的主题 » 如何在Python中从给定字符串中移除子字符串列表?

你可以用 str.replace() 将子字符串替换为 "" " " 替换后单词之间只有一个空格。你可以用 str.split() 和 str.join() 为了这个。

string = "Play soccer tomorrow from 2pm to 3pm @homies"

times = ["tomorrow", "from 2pm to 3pm"]

for time in times:
    string = string.replace(time, "")

print(" ".join(string.split()))
# Play soccer @homies

字符串在python中是不可变的,因此不能简单地使用 string.replace(time, "") . 你需要重新分配字符串 string = string.replace(time, "") .

6 年前
回复了 roadrunner 创建的主题 » 将Python列表转换为JSON文档

您还可以将结果更改为将文件名作为键,因为它们是唯一的:

{
    "SCAN1.txt": {
        "Filesize": 7196,
        "Lastmodified": 20191125.121049
    },
    "SCAN2.txt": {
        "Filesize": 3949,
        "Lastmodified": 20191125.121017
    },
    "SCAN3.txt": {
        "Filesize": 2766,
        "Lastmodified": 20191125.121056
    }
}

可实现如下(包括评论):

from collections import defaultdict
from json import dumps
from ast import literal_eval

lst = [
    "SCAN1.txt",
    "Lastmodified:20191125.121049",
    "Filesize:7196",
    "SCAN2.txt",
    "Lastmodified:20191125.121017",
    "Filesize:3949",
    "SCAN3.txt",
    "Lastmodified:20191125.121056",
    "Filesize:2766",
]


def group_file_documents(lst, prefix="SCAN"):
    # Use defaultdict of dicts to represent final JSON structure
    # Also can be serialized like normal dictionaries
    result = defaultdict(dict)

    current_file = None
    for item in lst:

        # Update current file name if starts with prefix
        if item.startswith(prefix):
            current_file = item
            continue

        # Ensure current file name is present
        if current_file:

            # Split key.values and strip whitespace, just in case
            key, value = map(str.strip, item.split(":"))

            # Convert to actual int/float value
            result[current_file][key] = literal_eval(value)

    return result

# Print serialized JSON file with sorted keys and indents of 4 spaces
print(dumps(group_file_documents(lst), sort_keys=True, indent=4))