根据空间分割段落并删除多余的空间

时间:2018-09-06 07:42:35

标签: python

我有一个段落,例如需要用空格将每个单词分开。

数据:

BigMart has collected 2013 sales data for 1559 products  across 10 stores in different cities. The aim is to build a predictive model and find out the sales of each product at a store.

Python    
java     
data scientist   

输出:

bigmart
has
collected
2013
sales
data
for
1559
products


across
10
stores
in
different
cities.
the
aim
is
to
build
a
predictive

产品之间以及整个产品之间都有很大的空间。有办法删除吗?

4 个答案:

答案 0 :(得分:3)

没有参数的

string.split()方法在空白处分割:

myText = "BigMart has collected"
splitText = myText.split()
print(splitText)

输出:

['BigMart', 'has', 'collected']

您可以在https://docs.python.org/2/library/string.html

上了解有关拆分方法的更多信息。

答案 1 :(得分:1)

s = '''BigMart has collected 2013 sales data for 1559 products  across 10 stores in 
      different cities. The aim is to build a predictive model and find out the sales 
      of each product at a store.

      Python    
      java     
      data scientist'''

for i in s.split():print(i)

#Output
BigMart
has
collected
2013
sales
data
for
1559
products
across
10
stores
in
different
cities.
The
aim
is
to
build
a
predictive
.
.

如果您希望将结果放入列表

print(s.split())

答案 2 :(得分:1)

如果要避免多余的空格,可以过滤掉并非“真”的项目:

test = "BigMart has collected 2013 sales data for 1559 products  across 10 stores in different cities. The aim is to build a predictive model and find out the sales of each product at a store."

words = [word for word in test.split(' ') if word]

for word in words:
  print(word)

答案 3 :(得分:1)

使用split()方法,您将获得每个单词作为列表中单独的字符串值。您还将获得标点符号(因此最后一个值将是“ store”。) 如果要在空间上拆分,请执行split(“”),但您将获得一个包含很多空格的列表。

相关问题