我有一个段落,例如需要用空格将每个单词分开。
数据:
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
产品之间以及整个产品之间都有很大的空间。有办法删除吗?
答案 0 :(得分:3)
string.split()方法在空白处分割:
myText = "BigMart has collected"
splitText = myText.split()
print(splitText)
输出:
['BigMart', 'has', 'collected']
上了解有关拆分方法的更多信息。
答案 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(“”),但您将获得一个包含很多空格的列表。