Python 在第二次出现字符后拆分文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36300158/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:42:50  来源:igfitidea点击:

Split text after the second occurrence of character

pythonpython-3.xstringsplit

提问by DBS

I need to split text before the second occurrence of the '-' character. What I have now is producing inconsistent results. I've tried various combinations of rsplitand read through and tried other solutions on SO, with no results.

我需要在第二次出现“-”字符之前拆分文本。我现在所拥有的是产生不一致的结果。我尝试了各种组合rsplit并通读并尝试了其他解决方案,但没有结果。

Sample file name to split: 'some-sample-filename-to-split'returned in data.filename. In this case, I would only like to have 'some-sample'returned.

要拆分的示例文件名:'some-sample-filename-to-split'data.filename. 在这种情况下,我只想'some-sample'回来。

fname, extname = os.path.splitext(data.filename)
file_label = fname.rsplit('/',1)[-1]
file_label2 = file_label.rsplit('-',maxsplit=3)
print(file_label2,'\n','---------------','\n')

回答by JRodDynamite

You can do something like this:

你可以这样做:

>>> a = "some-sample-filename-to-split"
>>> "-".join(a.split("-", 2)[:2])
'some-sample'

a.split("-", 2)will split the string upto the second occurrence of -.

a.split("-", 2)将字符串拆分到第二次出现-.

a.split("-", 2)[:2]will give the first 2 elements in the list. Then simply join the first 2 elements.

a.split("-", 2)[:2]将给出列表中的前 2 个元素。然后只需加入前 2 个元素。

OR

或者

You could use regular expression : ^([\w]+-[\w]+)

您可以使用正则表达式: ^([\w]+-[\w]+)

>>> import re
>>> reg = r'^([\w]+-[\w]+)'
>>> re.match(reg, a).group()
'some-sample'

EDIT:As discussed in the comments, here is what you need:

编辑:正如评论中所讨论的,这是您需要的:

def hyphen_split(a):
    if a.count("-") == 1:
        return a.split("-")[0]
    else:
        return "-".join(a.split("-", 2)[:2])

>>> hyphen_split("some-sample-filename-to-split")
'some-sample'
>>> hyphen_split("some-sample")
'some'

回答by Nuno André

A generic form to split a string into halves on the nth occurence of the separator would be:

在第 n 次出现分隔符时将字符串分成两半的通用形式是:

def split(strng, sep, pos):
    strng = strng.split(sep)
    return sep.join(strng[:pos]), sep.join(strng[pos:])

If posis negative it will count the occurrences from the end of string.

如果pos是负数,它将从字符串末尾计算出现次数。

>>> strng = 'some-sample-filename-to-split'
>>> split(strng, '-', 3)
('some-sample-filename', 'to-split')
>>> split(strng, '-', -4)
('some', 'sample-filename-to-split')
>>> split(strng, '-', 1000)
('some-sample-filename-to-split', '')
>>> split(strng, '-', -1000)
('', 'some-sample-filename-to-split')

回答by Mike Müller

You can use str.index():

您可以使用str.index()

def hyphen_split(s):
    pos = s.index('-')
    try:
        return s[:s.index('-', pos + 1)]
    except ValueError:
        return s[:pos]

test:

测试:

>>> hyphen_split("some-sample-filename-to-split")
'some-sample'
>>> hyphen_split("some-sample")
'some'

回答by Christian

You could use regular expressions:

您可以使用正则表达式:

import re

file_label = re.search('(.*?-.*?)-', fname).group(1)