我有一个段落,我需要用空格分隔每个单词。
数据:
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
产品之间和整个产品之间有很大的空间。有没有办法删除它?
没有参数的string.split()方法在空格上拆分:
myText = "BigMart has collected"
splitText = myText.split()
print(splitText)
输出:
['BigMart', 'has', 'collected']
您可以在以下网址上阅读有关拆分方法的更多信息:https://docs.python.org/2/library/string.html
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())
如果你想避免多余的空格,你可以过滤掉那些不是“真实”的物品:
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)
使用split()
方法,您将在列表中将每个单词作为分隔的字符串值。你也会得到标点符号(所以最后一个值将是“存储”。)如果你想分割空格,请做拆分(“”)但是你会得到一个包含很多空格的列表。