【问题标题】:Iterating through a string word by word逐字遍历字符串
【发布时间】:2015-08-06 01:41:26
【问题描述】:

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

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

上面给出了一个输出:

t
h
i
s

i
s

a

s
t
r
i
n
g

但我正在寻找以下输出:

this
is
a
string

【问题讨论】:

标签: python


【解决方案1】:

当你这样做时 -

for word in string:

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

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

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

【讨论】:

  • 嘿,有没有办法维护所有的空间并做同样的事情?
  • @MohitBhasi 也许你弄错了? str.split() 不是 insplace ,它只是返回拆分后的字符串列表,原始字符串仍然完好无损。
【解决方案2】:

这是一种方法:

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

输出:

this
is
a
string

【讨论】:

    【解决方案3】:
    for word in string.split():
        print word
    

    【讨论】:

    • 你应该解释split方法;不要期望每个人都知道它的作用或您使用它的原因。
    • 我的评论很简洁,但并不意味着侮辱。我只希望Stack Overflow 做到最好。仅代码的答案很难阅读和理解,尤其是对于那些“不知道”对您来说显而易见的东西的人。这就是他们在这里寻找答案的原因。
    【解决方案4】:

    使用nltk

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

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

    【讨论】:

      【解决方案5】:

      一种方法是使用字典。上面代码的问题是它计算字符串中的每个字母,而不是每个单词。要解决这个问题,你应该首先使用 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)
      

      【讨论】:

        【解决方案6】:
        s = 'hi how are you'
        l = list(map(lambda x: x,s.split()))
        print(l)
        

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

        【讨论】:

          猜你喜欢
          • 2013-01-18
          • 1970-01-01
          • 1970-01-01
          • 2014-04-02
          • 2018-05-15
          • 2011-08-27
          相关资源
          最近更新 更多