【问题标题】:Using a For Loop to Change Words in Strings to List Items使用 For 循环更改字符串中的单词以列出项目
【发布时间】:2018-07-19 18:15:42
【问题描述】:

我正在尝试使用for 循环来查找字符串中恰好包含一个字母e 的每个单词。

我的猜测是我需要使用for循环首先将字符串中的每个单词分隔到自己的列表中(例如,this is a string变成['this']['is']['a']、@987654328 @)

然后,我可以使用另一个 For 循环来检查每个单词/列表。

我的字符串存储在变量joke中。

我在构建 For 循环以将每个单词放入自己的列表时遇到问题。有什么建议?

j2 = []

for s in joke:
if s[0] in j2:
    j2[s[0]] = joke.split()
else:
    j2[s[0]] = s[0]
print(j2)

【问题讨论】:

  • 检查这个。 stackoverflow.com/questions/31845482/…。你不能使用for s in joke
  • 以后,变量名使用符号`代替"为了清楚起见。第一个暗示代码的一部分(如变量),第二个使它看起来像一个字符串

标签: python string list for-loop


【解决方案1】:

我会使用Counter:

from collections import Counter
joke = "A string with some words they contain letters"
j2 = []
for w in joke.split():
    d = Counter(w)
    if 'e' in d.keys():
        if d['e'] == 1:
            j2.append(w)

print(j2)

这会导致:

['some', 'they']

【讨论】:

    【解决方案2】:

    这是一种方式:

    mystr = 'this is a test string'    
    [i for i in mystr.split() if sum(k=='e' for k in i) == 1]   
    # test
    

    如果你需要一个显式循环:

    result = []
    for i in mystr:
        if sum(k=='e' for k in i) == 1:
            result.append(i)
    

    【讨论】:

      【解决方案3】:

      这是list comprehensions 的经典案例。要生成仅包含一个字母“e”的单词列表,您可以使用以下来源。

      words = [w for w in joke.split() if w.count('e') == 1]
      

      【讨论】:

      • 请注意,与其像您所说的那样为每个单词创建一个列表,不如像Hans' 答案那样创建一个包含所有单词的列表更有效。
      【解决方案4】:

      要查找只有一个字母“e”的单词,请使用正则表达式

      import re
      mywords = re.match("(\s)*[e](\s)*", 'this is your e string e')
      print(mywords)
      

      【讨论】:

        【解决方案5】:

        使用numpy 的另一种方法是完全反对:

        s = 'Where is my chocolate pizza'
        s_np = np.array(s.split())
        result = s_np[np.core.defchararray.count(s_np, 'e').astype(bool)]
        

        【讨论】:

          【解决方案6】:
          sentence = "The cow jumped over the moon."
          new_str = sentence.split()
          count = 0
          for i in new_str:
              if 'e' in i:
                  count+=1
                  print(i)
          print(count)
          

          【讨论】:

          • 我不确定这是否是您要查找的内容,但这会给您提供多少个“e”并打印带有字母“e”的单词
          猜你喜欢
          • 1970-01-01
          • 2021-10-11
          • 2020-01-22
          • 2019-06-05
          • 2012-09-01
          • 1970-01-01
          • 1970-01-01
          • 2020-05-22
          • 2022-11-12
          相关资源
          最近更新 更多