簡體   English   中英

逐字遍歷字符串

[英]Iterating through a string word by word

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

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

上面給出了一個 output:

t
h
i
s

i
s

a

s
t
r
i
n
g

但我正在尋找以下 output:

this
is
a
string

當你這樣做時——

for word in string:

您不是遍歷字符串中的單詞,而是遍歷字符串中的字符。 要遍歷單詞,您首先需要使用str.split()將字符串拆分為 words ,然后遍歷 that 。 例子 -

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

請注意, str.split() ,不通過任何參數分割所有空格(空格、多個空格、制表符、換行符等)。

這是一種方法:

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

輸出:

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

使用nltk

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

您可以使用TweetTokenizer來解析帶有表情符號等的隨意文本。

一種方法是使用字典。 上面代碼的問題是它計算字符串中的每個字母,而不是每個單詞。 要解決這個問題,首先應該使用 split() 方法將字符串變成一個列表,然后創建一個變量,將列表中的每個逗號作為它自己的值。 每當一個單詞以字典的形式出現在字符串中時,下面的代碼就會返回。

    s = input('Enter a string to see if strings are repeated: ')
    d = dict()
    p = s.split()
    word = ','
    for word in p:
        if word not in d:
            d[word] = 1
        else:
            d[word] += 1
    print (d)

你也可以試試這個方法:

sentence_1 = "這是一個字符串"

list = sentence_1.split()

對於列表中的 i:打印 (i)

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM