【问题标题】:How do I split a string BEFORE a certain character?如何在某个字符之前拆分字符串?
【发布时间】:2016-03-07 02:49:24
【问题描述】:
timeline = '''
1961 - Second child, John, is born. 1963 - Is ordained as a Presbyterian minister. Makes his on-camera debut as host of a series of 15-minute episodes for children produced in Toronto. The program is titled "Mister Rogers." 1964 - Returns to Pittsburgh
    and turns his 15-minute show into the half-hour "Mister Rogers' Neighborhood." 1968 - "Mister Rogers' Neighborhood" debuts on PBS and wins the first of its several Emmy Awards. Rogers is appointed chairman of the Forum on Mass Media and Child Development
    of the White House Conference on Youth. 1969 - Wins the first of his two George Foster Peabody Awards for television excellence. Fred Rogers readies the opening pitch to start the Pirates' season in 1988. (Post-Gazette archives) 1971 - Forms his production
    company, Family Communications Inc. 1975 - Ceases production on "Mister Rogers' Neighborhood," which continues to air on PBS in reruns. 1978 - Creates the PBS series "Old Friends, New Friends," focusing on older people. 1979 - Production resumes on
    "Mister Rogers' Neighborhood." 1981 - Eddie Murphy plays an inner-city children's show host in his "Mister Robinson's Neighborhood" sketch on "Saturday Night Live," which is probably the most famous of the many "Mister Rogers" spoofs. 1984 - The Smithsonian
    Institution in Washington makes Fred Rogers' trademark sweater part of its permanent collection. Rogers forces the fast-food chain Burger King to remove ads featuring a Mister Rogers lookalike. 1987 - Appears on a children's TV show in the Soviet
    Union and reciprocates by having a Soviet host appear on his show later in the year. 1989 - "Mister Rogers' Neighborhood of Make Believe" opens as an attraction at Idlewild Park. 1990 - Sues the Ku Klux Klan and forces the organization to stop playing
    racist telephone recordings featuring imitations of Fred Rogers' voice, speech patterns and theme song. 1991 - Tapes spots for PBS on the eve of the Gulf War to reassure children that they will be all right if hostilities occur. 1996 - TV Guide names
    Fred Rogers one of the 50 greatest TV stars of all time. Rogers makes his only appearance as someone other than himself when he takes a cameo role as a preacher on the drama series "Dr. Quinn, Medicine Woman," which he says is one of his favorite
    shows. 1997 - Is honored for lifetime achievement by the National Academy of Television Arts and Sciences (who hand out the Emmy Awards) and by the Television Critics Association. Named Pittsburgher of the Year by Pittsburgh magazine. 1998 - Gets
    a star on the Hollywood Walk of Fame. The Pittsburgh Children's Museum opens a Mister Rogers exhibit. 1999 - Is inducted into the Television Hall of Fame. 2000 - Unveils a planetarium show featuring "Neighborhood" characters at the Carnegie Science
    Center; ceases production on "Mister Rogers' Neighborhood." 2001 - Last original episodes of "Mister Rogers' Neighborhood" airs on PBS. 2002 - In July, is presented the Presidential Medal of Freedom, the nation's highest civilian honor. Filmed PBS
    public service announcements in August encouraging parents to read to their children and giving them advice on how to handle the first anniversary of the Sept. 11, 2001, terrorist attacks. Is named grand marshal of the Tournament of Roses Parade in
    Pasadena, Calif., with Bill Cosby and Art Linkletter. The theme: "Children's Wishes, Dreams and Imagination." 2003 - Dies of stomach cancer at age 74.

'''

我的目标是使它成为一个字典,其中键是年份,值是时间轴上的事件。但是,我遇到了一些麻烦。

我想首先将时间线拆分为一个列表,如下所示:{key, value, key, value},然后将其转换为 dict。我想在“ - ”之前将字符串拆分为 5 或 6 个字符以完成此操作,但我不知道该怎么做。谁能帮帮我?

编辑: 想出了这个可能的解决方案 -

timeline = timeline.replace("\n","")
timeline = timeline.replace("\\","")
timeline = timeline.replace("19","zz19")
timeline = timeline.replace("20","zz20")
timeline = timeline.split(" - ")

所以我基本上是这样结束的:

['zz1961', 'Second child, John, is born. zz1963', 'Is ordained as a Presbyterian minister. Makes his on-camera debut as host of a series of 15-minute episodes for children produced in Toronto. The program is titled "Mister Rogers." zz1964', 'Returns to Pittsburgh    and turns his 15-minute show into the half-hour "Mister Rogers\' Neighborhood." zz1968', '"Mister Rogers\' Neighborhood" debuts on PBS and wins the first of its several Emmy Awards. Rogers is appointed chairman of the Forum on Mass Media and Child Development    of the White House Conference on Youth. zz1969', "Wins the first of his two George Foster Peabody Awards for television excellence. Fred Rogers readies the opening pitch to start the Pirates' season in zz1988. (Post-Gazette archives) zz1971", 'Forms his production    company, Family Communications Inc. zz1975', 'Ceases production on "Mister Rogers\' Neighborhood," which continues to air on PBS in reruns. zz1978', 'Creates the PBS series "Old Friends, New Friends," focusing on older people. zz1979', 'Production resumes on    "Mister Rogers\' Neighborhood." zz1981', 'Eddie Murphy plays an inner-city children\'s show host in his "Mister Robinson\'s Neighborhood" sketch on "Saturday Night Live," which is probably the most famous of the many "Mister Rogers" spoofs. zz1984', "The Smithsonian    Institution in Washington makes Fred Rogers' trademark sweater part of its permanent collection. Rogers forces the fast-food chain Burger King to remove ads featuring a Mister Rogers lookalike. zz1987", "Appears on a children's TV show in the Soviet    Union and reciprocates by having a Soviet host appear on his show later in the year. zz1989", '"Mister Rogers\' Neighborhood of Make Believe" opens as an attraction at Idlewild Park. zz1990', "Sues the Ku Klux Klan and forces the organization to stop playing    racist telephone recordings featuring imitations of Fred Rogers' voice, speech patterns and theme song. zz1991", 'Tapes spots for PBS on the eve of the Gulf War to reassure children that they will be all right if hostilities occur. zz1996', 'TV Guide names    Fred Rogers one of the 50 greatest TV stars of all time. Rogers makes his only appearance as someone other than himself when he takes a cameo role as a preacher on the drama series "Dr. Quinn, Medicine Woman," which he says is one of his favorite    shows. zz1997', 'Is honored for lifetime achievement by the National Academy of Television Arts and Sciences (who hand out the Emmy Awards) and by the Television Critics Association. Named Pittsburgher of the Year by Pittsburgh magazine. zz1998', "Gets    a star on the Hollywood Walk of Fame. The Pittsburgh Children's Museum opens a Mister Rogers exhibit. zz1999", 'Is inducted into the Television Hall of Fame. zz2000', 'Unveils a planetarium show featuring "Neighborhood" characters at the Carnegie Science    Center; ceases production on "Mister Rogers\' Neighborhood." zz2001', 'Last original episodes of "Mister Rogers\' Neighborhood" airs on PBS. zz2002', 'In July, is presented the Presidential Medal of Freedom, the nation\'s highest civilian honor. Filmed PBS    public service announcements in August encouraging parents to read to their children and giving them advice on how to handle the first anniversary of the Sept. 11, zz2001, terrorist attacks. Is named grand marshal of the Tournament of Roses Parade in    Pasadena, Calif., with Bill Cosby and Art Linkletter. The theme: "Children\'s Wishes, Dreams and Imagination." zz2003', 'Dies of stomach cancer at age 74.']

所以我想用“zz”分割这个字符串,唯一的问题是我不能把它分割两次,因为它已经是一个列表。显然我可以连接列表,但是我会遇到和现在一样的问题。

试过这样做:

for i in timeline:
    i = i.split("zz")

但它不起作用:(

【问题讨论】:

  • 您预期的最终结果是什么。我也很困惑你为什么要先变成 list 然后 dict。
  • 你能给出一个更简单的例子,以及预期的输出吗?
  • 开始于:timeline = ''' 1961 - 第二个孩子约翰出生。 1963 - 被任命为长老会牧师。作为在多伦多制作的一系列 15 分钟儿童剧集的主持人,他在镜头前首次亮相。该节目名为“罗杰斯先生”。 ''' 列表的预期结果:时间线 = [“1961”,“第二个孩子,约翰出生。”,“1963”,“被任命为长老会牧师。作为系列节目的主持人首次亮相在多伦多为儿童制作的 15 分钟剧集。节目名为“罗杰斯先生”。]
  • 如果文本中间有 19 或 20 怎么办?
  • 板球好问题。谢天谢地,它不是......但如果是这样,它可能会变得更加复杂。如果是这样的话,最好有一个替换的占位符,所以我可以说:timeline = timeline.replace("20##","zz20##") 其中 # 是占位符

标签: python string list dictionary split


【解决方案1】:

你可以这样制作字典:

parts = timeline.replace('\n','').split(" - ")
d = dict()
for x in range(len(parts) - 1):
    d[parts[x][-4:]] = parts[x + 1][:len(parts[x+1]) - 4]

由于您的分隔符显然是" - ",因此您将拥有一组项目,例如:

'1961'
'blablablablabla. 1963'
'blablablablabla. 1968'
'blablablablabla. 1969'
'blablablablabla'

那么您只需要将文本中的最后 4 个字符与除最后四个字符之外的下一个文本配对。因此,简单的拆分和切片将适合您。

用这个来显示结果:

for a in d:
    print(a + " " + d[a])

这是我得到的:

1975 Ceases production on "Mister Rogers' Neighborhood," which continues to air on PBS in reruns. 
1968 "Mister Rogers' Neighborhood" debuts on PBS and wins the first of its several Emmy Awards. Rogers is appointed chairman of the Forum on Mass Media and Child Development    of the White House Conference on Youth. 
2001 Last original episodes of "Mister Rogers' Neighborhood" airs on PBS. 
1990 Sues the Ku Klux Klan and forces the organization to stop playing    racist telephone recordings featuring imitations of Fred Rogers' voice, speech patterns and theme song. 
2002 In July, is presented the Presidential Medal of Freedom, the nation's highest civilian honor. Filmed PBS    public service announcements in August encouraging parents to read to their children and giving them advice on how to handle the first anniversary of the Sept. 11, 2001, terrorist attacks. Is named grand marshal of the Tournament of Roses Parade in    Pasadena, Calif., with Bill Cosby and Art Linkletter. The theme: "Children's Wishes, Dreams and Imagination." 
1989 "Mister Rogers' Neighborhood of Make Believe" opens as an attraction at Idlewild Park. 
1996 TV Guide names    Fred Rogers one of the 50 greatest TV stars of all time. Rogers makes his only appearance as someone other than himself when he takes a cameo role as a preacher on the drama series "Dr. Quinn, Medicine Woman," which he says is one of his favorite    shows. 
1987 Appears on a children's TV show in the Soviet    Union and reciprocates by having a Soviet host appear on his show later in the year. 
1963 Is ordained as a Presbyterian minister. Makes his on-camera debut as host of a series of 15-minute episodes for children produced in Toronto. The program is titled "Mister Rogers." 
1984 The Smithsonian    Institution in Washington makes Fred Rogers' trademark sweater part of its permanent collection. Rogers forces the fast-food chain Burger King to remove ads featuring a Mister Rogers lookalike. 
1971 Forms his production    company, Family Communications Inc. 
1991 Tapes spots for PBS on the eve of the Gulf War to reassure children that they will be all right if hostilities occur. 
1997 Is honored for lifetime achievement by the National Academy of Television Arts and Sciences (who hand out the Emmy Awards) and by the Television Critics Association. Named Pittsburgher of the Year by Pittsburgh magazine. 
1999 Is inducted into the Television Hall of Fame. 
1964 Returns to Pittsburgh    and turns his 15-minute show into the half-hour "Mister Rogers' Neighborhood." 
2000 Unveils a planetarium show featuring "Neighborhood" characters at the Carnegie Science    Center; ceases production on "Mister Rogers' Neighborhood." 
1981 Eddie Murphy plays an inner-city children's show host in his "Mister Robinson's Neighborhood" sketch on "Saturday Night Live," which is probably the most famous of the many "Mister Rogers" spoofs. 
1978 Creates the PBS series "Old Friends, New Friends," focusing on older people. 
1969 Wins the first of his two George Foster Peabody Awards for television excellence. Fred Rogers readies the opening pitch to start the Pirates' season in 1988. (Post-Gazette archives) 
1961 Second child, John, is born. 
2003 Dies of stomach cancer at age
1998 Gets    a star on the Hollywood Walk of Fame. The Pittsburgh Children's Museum opens a Mister Rogers exhibit. 
1979 Production resumes on    "Mister Rogers' Neighborhood." 

请注意,字典是无序的。如果您需要订购,请使用OrderedDict

有序字典就像这样简单的字典:

import collections
parts = timeline.replace('\n','').split(" - ")
od = collections.OrderedDict()
for x in range(len(parts) - 1):
    od[parts[x][-4:]] = parts[x + 1][:len(parts[x+1]) - 4]

然后使用这个:

for a in od:
    print(a + " " + od[a])

结果将被排序:

1961 Second child, John, is born. 
1963 Is ordained as a Presbyterian minister. Makes his on-camera debut as host of a series of 15-minute episodes for children produced in Toronto. The program is titled "Mister Rogers." 
1964 Returns to Pittsburgh    and turns his 15-minute show into the half-hour "Mister Rogers' Neighborhood." 
1968 "Mister Rogers' Neighborhood" debuts on PBS and wins the first of its several Emmy Awards. Rogers is appointed chairman of the Forum on Mass Media and Child Development    of the White House Conference on Youth. 
1969 Wins the first of his two George Foster Peabody Awards for television excellence. Fred Rogers readies the opening pitch to start the Pirates' season in 1988. (Post-Gazette archives) 
1971 Forms his production    company, Family Communications Inc. 
1975 Ceases production on "Mister Rogers' Neighborhood," which continues to air on PBS in reruns. 
1978 Creates the PBS series "Old Friends, New Friends," focusing on older people. 
1979 Production resumes on    "Mister Rogers' Neighborhood." 
1981 Eddie Murphy plays an inner-city children's show host in his "Mister Robinson's Neighborhood" sketch on "Saturday Night Live," which is probably the most famous of the many "Mister Rogers" spoofs. 
1984 The Smithsonian    Institution in Washington makes Fred Rogers' trademark sweater part of its permanent collection. Rogers forces the fast-food chain Burger King to remove ads featuring a Mister Rogers lookalike. 
1987 Appears on a children's TV show in the Soviet    Union and reciprocates by having a Soviet host appear on his show later in the year. 
1989 "Mister Rogers' Neighborhood of Make Believe" opens as an attraction at Idlewild Park. 
1990 Sues the Ku Klux Klan and forces the organization to stop playing    racist telephone recordings featuring imitations of Fred Rogers' voice, speech patterns and theme song. 
1991 Tapes spots for PBS on the eve of the Gulf War to reassure children that they will be all right if hostilities occur. 
1996 TV Guide names    Fred Rogers one of the 50 greatest TV stars of all time. Rogers makes his only appearance as someone other than himself when he takes a cameo role as a preacher on the drama series "Dr. Quinn, Medicine Woman," which he says is one of his favorite    shows. 
1997 Is honored for lifetime achievement by the National Academy of Television Arts and Sciences (who hand out the Emmy Awards) and by the Television Critics Association. Named Pittsburgher of the Year by Pittsburgh magazine. 
1998 Gets    a star on the Hollywood Walk of Fame. The Pittsburgh Children's Museum opens a Mister Rogers exhibit. 
1999 Is inducted into the Television Hall of Fame. 
2000 Unveils a planetarium show featuring "Neighborhood" characters at the Carnegie Science    Center; ceases production on "Mister Rogers' Neighborhood." 
2001 Last original episodes of "Mister Rogers' Neighborhood" airs on PBS. 
2002 In July, is presented the Presidential Medal of Freedom, the nation's highest civilian honor. Filmed PBS    public service announcements in August encouraging parents to read to their children and giving them advice on how to handle the first anniversary of the Sept. 11, 2001, terrorist attacks. Is named grand marshal of the Tournament of Roses Parade in    Pasadena, Calif., with Bill Cosby and Art Linkletter. The theme: "Children's Wishes, Dreams and Imagination." 
2003 Dies of stomach cancer at age

【讨论】:

  • 谢谢,我试试这个!
  • 谢谢这工作很好,唯一的事情是它在所有撇号前添加了一个“\”。 (例如 George's => George\'s)
  • 怎么会这样?
  • @GeorgeTye 这不是真正的',它只是显示。当我打印它时,它消失了。看? :) 可能只是调试表示',但如果你打印出来,撇号前没有反斜杠
  • 哦,太棒了!所以我不是真的 100% 理解第 3 行和第 4 行在你原来的报价中是如何工作的,但我今晚要分析一下。明天我可能还有一些问题……希望你留下来回答他们,伊恩!谢谢一百万。
【解决方案2】:

让我们使用正则表达式进行拆分!

import re
stripped_string = timeline.replace('\n', '').strip() # whitespaces go away
splitted = re.split('(\d{4}) - ', stripped_string) # split to ['', year1, event1, year2, event2, ...]
lst = splitted[1:] # first empty split goes away
keys = lst[0::2] # get years
values = lst[1::2] # get events
dic = dict(zip(keys, values))

您可以进一步使其更具体。例如,如果您知道年份是 19xx 或 20xx,那么:

splitted = re.split('((?:19|20)\d\d) - ', stripped_string)

也可以。

此外,由于您有明确的keysvalues,您可以轻松地做几件事,例如去除values 中每个元素的空格。例如:

values = [event.strip() for event in lst[1::2]]

结果如下:

>>> print("\n".join("{}: {}".format(k, v) for k, v in dic.items()))
1989: "Mister Rogers' Neighborhood of Make Believe" opens as an attraction at Idlewild Park.
1987: Appears on a children's TV show in the Soviet    Union and reciprocates by having a Soviet host appear on his show later in the year.
1984: The Smithsonian    Institution in Washington makes Fred Rogers' trademark sweater part of its permanent collection. Rogers forces the fast-food chain Burger King to remove ads featuring a Mister Rogers lookalike.
1968: "Mister Rogers' Neighborhood" debuts on PBS and wins the first of its several Emmy Awards. Rogers is appointed chairman of the Forum on Mass Media and Child Development    of the White House Conference on Youth.
1969: Wins the first of his two George Foster Peabody Awards for television excellence. Fred Rogers readies the opening pitch to start the Pirates' season in 1988. (Post-Gazette archives)
1981: Eddie Murphy plays an inner-city children's show host in his "Mister Robinson's Neighborhood" sketch on "Saturday Night Live," which is probably the most famous of the many "Mister Rogers" spoofs.
1964: Returns to Pittsburgh    and turns his 15-minute show into the half-hour "Mister Rogers' Neighborhood."
1961: Second child, John, is born.
1963: Is ordained as a Presbyterian minister. Makes his on-camera debut as host of a series of 15-minute episodes for children produced in Toronto. The program is titled "Mister Rogers."
1991: Tapes spots for PBS on the eve of the Gulf War to reassure children that they will be all right if hostilities occur.
1990: Sues the Ku Klux Klan and forces the organization to stop playing    racist telephone recordings featuring imitations of Fred Rogers' voice, speech patterns and theme song.
1997: Is honored for lifetime achievement by the National Academy of Television Arts and Sciences (who hand out the Emmy Awards) and by the Television Critics Association. Named Pittsburgher of the Year by Pittsburgh magazine.
1979: Production resumes on    "Mister Rogers' Neighborhood."
1996: TV Guide names    Fred Rogers one of the 50 greatest TV stars of all time. Rogers makes his only appearance as someone other than himself when he takes a cameo role as a preacher on the drama series "Dr. Quinn, Medicine Woman," which he says is one of his favorite    shows.
1999: Is inducted into the Television Hall of Fame.
1998: Gets    a star on the Hollywood Walk of Fame. The Pittsburgh Children's Museum opens a Mister Rogers exhibit.
1975: Ceases production on "Mister Rogers' Neighborhood," which continues to air on PBS in reruns.
1978: Creates the PBS series "Old Friends, New Friends," focusing on older people.
1971: Forms his production    company, Family Communications Inc.
2002: In July, is presented the Presidential Medal of Freedom, the nation's highest civilian honor. Filmed PBS    public service announcements in August encouraging parents to read to their children and giving them advice on how to handle the first anniversary of the Sept. 11, 2001, terrorist attacks. Is named grand marshal of the Tournament of Roses Parade in    Pasadena, Calif., with Bill Cosby and Art Linkletter. The theme: "Children's Wishes, Dreams and Imagination."
2003: Dies of stomach cancer at age 74.
2000: Unveils a planetarium show featuring "Neighborhood" characters at the Carnegie Science    Center; ceases production on "Mister Rogers' Neighborhood."
2001: Last original episodes of "Mister Rogers' Neighborhood" airs on PBS.

【讨论】:

  • 谢谢,我试试这个!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-04
  • 2023-04-06
  • 1970-01-01
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多