程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在python中拆分乱序字符串大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在python中拆分乱序字符串?

开发过程中遇到在python中拆分乱序字符串的问题如何解决?下面主要结合日常开发的经验,给出你关于在python中拆分乱序字符串的解决方法建议,希望对你解决在python中拆分乱序字符串有所启发或帮助;

我正在阅读看起来像这样的文本文件

file1.txt:
header A
blab
iuyt
header B
bkas
rtyu
header C
asdf
file2.txt:
header B
asDW
header A
hufd
ousu
header C
dfsn

文件末尾可能是换行符、空格或什么都没有。所有文件中的标题都相同,但顺序可能与上述不同。

我想映射它,以便第一个输入的 a = blab\niuyt 或第二个输入的 a = hufd\nousu。

解决方法

我不确定我是否完全理解您的问题。在我看来,您好像想要输入:

XABCDE

或者,等效地(至少就我在您的符号中可以看出):

BCXADE
DEBCXA

并返回一个像

这样的映射
{"x": "A","b": "C","d": "E"}

(这是表示名称-值对的一种方式)。

这样对吗?如果是这样:

# This is the input.
c = "XABCDE"

# This is a Dictionary comprehension,one way
# of creaTing a set of key-value pairs.
{
    c[idx].lower(): c[idx + 1]      # Map the first element of each pair to the second.
    for idx in range(0,len(C),2)  # Iterate over the pairs in the String. 
}
,

自从我最初的回答以来,这个问题已经进行了实质性的编辑,所以我要添加一个单独的答案。

OP 的输入如下:有一个文件 foo.txt,内容如下:

Header A
blab
iuyt
Header B
bkas
rtyu
Header C
asdf

OP 的预期输出是将标题 values 映射到标题后面的内容(不是行)的字典,即:

{
    "A": "blab\niuyt","B": "bkas\nrtyu","C": "asdf"
}

注意每个新标题之前的最后一个尾随行分隔符 (\n) 不应被包含在内。

一种方法:

import re

from collections import defaultDict

# Given something like "Header A" with a Trailing newline,# this will match "A" under group "key". The header formats
# in the example are simple enough that you could fetch the
# value using _,group = line.split(" "),but this accomodates
# more complex formats. Note that this regular expression 
# assumes each header will be followed by at leasT ONE line
# of data in a file!
PATTERN = re.compile(r"^Header\s*(?P<key>.+)(\r\n|\r|\n)")

# Using defaultDict with an str constructor means we don't have to check 
# for key existence before attempTing an append. check the standard library
# documentation for more info:
# https://docs.python.org/3/library/collections.html#collections.defaultDict
structured_output = defaultDict(str)

with open("txt","r") as handle:
    last_match = None  # Track the second-last match we made.

    for line in handle:
        maybe_match = PATTERN.match(linE)

        if maybe_match:  # We've matched a new header group. Strip the Trailing newline from preceding,if any.
            # This is either (a) the FIRST header we're matching or (b) the n-th header.
            # In the first case,structured_output[key] returns "" (see defaultDict),and "".rStrip("\n")
            # is "". In the second case,we Strip the last newline from the previous group (per the speC).
            group = (last_match or maybe_match).group("key")
            structured_output[group] = structured_output[group].rStrip()

            # Move the last_match "pointer" forWARD to the 
            # new header.
            last_match = maybe_match

        else:  # This is not a header,it's a line of data: append it.
            structured_output[last_match.group("key")] += line

    # Once we've run off the end of the file,we should still rStrip the _last_ group.
    structured_output[last_match.group("key")] = structured_output[last_match.group("key")].rStrip()
,

使用迭代器:

it = iter(String1)
res = {C: next(it) for c in it}

大佬总结

以上是大佬教程为你收集整理的在python中拆分乱序字符串全部内容,希望文章能够帮你解决在python中拆分乱序字符串所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: