如何在selenium python中每两行之后添加逗号?

2024-10-01 07:48:16 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我在每一行后面都有逗号,但我需要在每两行后面插入逗号。这是我正在编写的文本。 产品规格:

LEVERANDØRENS VARENUMMER
31358DC2
EAN NUMMER
4005176465017

这是我的密码:

specification.text.replace("\n",",").strip()

我的代码在每一行的末尾给我逗号,但我需要在每两行后面加逗号。以下是我的结果:

LEVERANDØRENS VARENUMMER,31358DC2,EAN NUMMER,4005176465017

我的预期结果如下:

LEVERANDØRENS VARENUMMER 31358DC2,EAN NUMMER 4005176465017

Tags: 代码text文本密码eanreplacespecificationstrip
3条回答

编辑:我只建议在您试图避免使用外部库时使用此方法。如果您可以访问像itertools这样的库(在Jason的回答中提到),您应该使用它们


这并不完全是小事。我组合的这个函数应该满足您的要求(增加了每N个字符执行一次的功能,而不仅仅是每两个字符执行一次)

def replaceEveryNth(string: str, replace: str, replace_with: str, n: int):
    out = ""
    str_frags = string.split(replace) #split the input string into substrings
    count = 1
    for frag in str_frags[:len(str_frags)-1]:
        out += frag #add substring to output string
        if count % n == 0: #Replace nth character
            out += replace_with
        else: #Use original character
            out += replace
        count += 1
    out += str_frags[len(str_frags)-1] #add last string fragment
    return out

在您的特定情况下,您可以这样使用:

replaceEveryNth(text, "\n", ",", 2).replace("\n", " ")

您可以编写一个生成器,成对地迭代行。用空格连接它们,然后用逗号连接那个

text = """LEVERANDØRENS VARENUMMER
31358DC2
EAN NUMMER
4005176465017"""

def grab_2(seq):
    iseq = iter(seq)
    while True:
        try:
            yield next(iseq), next(iseq)
        except StopIteration:
            break

out = ",".join(" ".join(vals) for vals in grab_2(text.split("\n")))
print(out)

您可以使用pythonshell来探索这个解决方案,并根据需要添加功能

>>> text = """LEVERANDØRENS VARENUMMER
... 31358DC2
... EAN NUMMER
... 4005176465017"""
>>> 
>>> def grab_2(seq):
...     iseq = iter(seq)
...     while True:
...         try:
...             yield next(iseq), next(iseq)
...         except StopIteration:
...             break
... 
>>> 

拆分该行将为您提供一个行列表,如果您愿意,可以进一步处理这些行

>>> lines = text.split("\n")
>>> lines
['LEVERANDØRENS VARENUMMER', '31358DC2', 'EAN NUMMER', '4005176465017']

一次抓取两行可以得到元组

>>> grabbed = list(grab_2(lines))
>>> for g in grabbed:
...     print(g)
... 
('LEVERANDØRENS VARENUMMER', '31358DC2')
('EAN NUMMER', '4005176465017')

这些块可以通过多种方式进行处理。除了与空格连接外,还可以使用格式说明符

>>> for g in grabbed:
...     print("{0};{1}\n".format(*g), end="")
... 
LEVERANDØRENS VARENUMMER;31358DC2
EAN NUMMER;4005176465017

您可以使用此行以逗号连接每两行:

from itertools import izip_longest as izip # For Python 2
from itertools import zip_longest as izip # For Python 3

splitted = specification.text.split('\n')
text = ', '.join([' '.join([first, second]) if second else first for first, second in izip(splitted[::2], splitted[1::2])])
print(text)

输出:

'LEVERANDØRENS VARENUMMER 31358DC2, EAN NUMMER 4005176465017'

另外,如果您知道行数始终为偶数,那么您可以简化解决方案,只需zip即可解决问题:

text = ', '.join([' '.join([first, second]) for first, second in zip(splitted[::2], splitted[1::2])])

相关问题 更多 >