我想从一个句子中删除逗号,并将所有其他单词(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
.
.
.
我该怎么做才能防止这种情况? 我已经尝试过替换方法,但是它不起作用。
答案 0 :(得分:1)
您的问题似乎是逗号和此处的下一个单词之间没有空格:academy,and
您可以通过确保有一个空格来解决此问题,以便在使用b=list(a)
时该函数将实际上将每个单词分成列表的不同元素。
答案 1 :(得分:1)
假设,
和输入 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
在空白处。
答案 2 :(得分:1)
这可能就是您想要的,我看到您忘记用空格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.']
答案 3 :(得分:1)
如果您认为单词是由空格隔开的一系列字符,则如果不使用替换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()