【问题标题】:separate words in a sentence that has comma between them [duplicate]句子中用逗号分隔的单词[重复]
【发布时间】:2019-01-24 17:39:22
【问题描述】:

我想从一个句子中删除逗号并将所有其他单词(a-z)分开并一个一个打印出来。

a = input()
b=list(a)                      //to remove punctuations
for item in list(b):           //to prevent "index out of range" error. 
    for j in range(len(l)):
        if(item==','):
            b.remove(item)
            break
c="".join(b)                  //sentence without commas
c=c.split()
print(c)

我的输入是:

The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.

当我删除逗号时:

... founded as a standard academyand developed to a university...

当我拆分单词时:

The
university
.
.
.
academyand
.
.
.

我能做些什么来防止这种情况发生? 我已经尝试过替换方法,但它不起作用。

【问题讨论】:

标签: python


【解决方案1】:

您的问题似乎是逗号和下一个单词之间没有空格:academy,and 您可以通过确保有空格来解决这个问题,因此当您使用b=list(a) 时,该函数实际上会分隔每个单词到列表的不同元素中。

【讨论】:

    【解决方案2】:

    假设, 和输入1 中的下一个单词之间没有空格,您可以用空格替换,,然后执行split

    s = 'The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.'
    
    print(s.replace(',', ' ').split())
    # ['The', 'university', 'was', 'founded', 'as', 'a', 'standard', 'academy', 'and', 'developed', 'to', 'a', 'university', 'of', 'technology', 'by', 'Habib', 'Nafisi.']
    

    或者,您也可以试试regex

    import re
    
    s = 'The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi.'
    
    print(re.split(r' |,', s))
    

    1注意:即使您在 , 之后有空格(多个),这仍然有效,因为最终您在空格上 split

    【讨论】:

      【解决方案3】:

      这可能是你想要的,我看到你忘了replace 逗号和空格。

      stri = """ The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi."""
      stri.replace(",", " ")
      print(stri.split())
      

      会给你一个列表中的输出:

      ['The', 'university', 'was', 'founded', 'as', 'a', 'standard', 'academy,and', 'developed', 'to', 'a', 'university', 'of', 'technology', 'by', 'Habib', 'Nafisi.']
      

      【讨论】:

        【解决方案4】:

        如果你认为单词是由空格分隔的一系列字符,如果你将 a 替换为空,那么它们之间将没有空格,它会认为它是一个单词。

        最简单的方法是将逗号替换为空格,然后根据空格进行拆分:

        my_string = "The university was founded as a standard academy,and developed to a university of technology by Habib Nafisi."
        list_of_words = my_string.replace(",", " ").split()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-17
          • 1970-01-01
          • 2021-01-29
          • 2020-01-10
          • 2012-09-22
          • 2019-12-12
          • 1970-01-01
          相关资源
          最近更新 更多