大佬教程收集整理的这篇文章主要介绍了在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,请注明来意。