Python 逐字遍历字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31845482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:39:10  来源:igfitidea点击:

Iterating through a string word by word

python

提问by Mohit Bhasi

I wanted to know how to iterate through a string word by word.

我想知道如何逐字遍历字符串。

string = "this is a string"
for word in string:
    print (word)

The above gives an output:

上面给出了一个输出:

t

h

i

s

i

s

a

s

t

r

i

n

g

H

一世

一世

一种

r

一世

n

G

But I am looking for the following output:

但我正在寻找以下输出:

this

is

a

string

这个

一种

细绳

采纳答案by Anand S Kumar

When you do -

当你这样做时——

for word in string:

You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split(), and then iterate through that . Example -

您不是遍历字符串中的单词,而是遍历字符串中的字符。要遍历单词,您首先需要将字符串拆分为 words ,使用str.split(),然后遍历 that 。例子 -

my_string = "this is a string"
for word in my_string.split():
    print (word)

Please note, str.split(), without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).

请注意,str.split(), 不传递任何由所有空格(空格、多个空格、制表符、换行符等)分割的参数。

回答by Joe T. Boka

This is one way to do it:

这是一种方法:

string = "this is a string"
ssplit = string.split()
for word in ssplit:
    print (word)

Output:

输出:

this
is
a
string

回答by Connor

for word in string.split():
    print word

回答by no?????z???

Using nltk.

使用nltk

from nltk.tokenize import sent_tokenize, word_tokenize
sentences = sent_tokenize("This is a string.")
words_in_each_sentence = word_tokenize(sentences)

You may use TweetTokenizerfor parsing casual text with emoticons and such.

您可以使用TweetTokenizer来解析带有表情符号等的随意文本。

回答by Nandu Software Engineer

s = 'hi how are you'
l = list(map(lambda x: x,s.split()))
print(l)

Output: ['hi', 'how', 'are', 'you']

输出: ['hi', 'how', 'are', 'you']