Python中的字符积累

Python中的字符积累,python,Python,所以我有一个文本文件,在这个文件中是这样的。。。(只是一点点) 现在,计算每行文本中没有字母“e”的单词长度。所以在第一行中,它应该有4个,然后是5个,然后是17个,以此类推 我现在的代码是 for line in open("textname.txt"): line_strip = line.strip() line_strip_split = line_strip.split() for word in line_strip_split: if "e" not in wo

所以我有一个文本文件,在这个文件中是这样的。。。(只是一点点)

现在,计算每行文本中没有字母“e”的单词长度。所以在第一行中,它应该有4个,然后是5个,然后是17个,以此类推

我现在的代码是

for line in open("textname.txt"):
  line_strip = line.strip()
  line_strip_split = line_strip.split()
  for word in line_strip_split:
    if "e" not in word:
     word_e = word


     print (len(word_e))
我的解释是:通过删除空格将每个单词从彼此中剥离出来,这样它就变成了['feel'、'at'、'its'、'kindled'、'core']等等。然后我们将每个单词拆分,因为我们在删除带有“e”的单词时可以单独考虑它?。所以我们想要不带e的单词,然后打印字符串的长度

但是,这会通过拆分然后拆分字符串将每个单词分隔成不同的行吗?因此,这并不是将每行中的所有单词加在一起,而是将它们分开,因此答案变成“4/2/3”

试试这个:

for line in open("textname.txt"):
    line_strip = line.strip()
    line_strip_split = line_strip.split()
    words_with_no_e = []
    for word in line_strip_split:
        if "e" not in word:
            # Adding words without e to a new list
            words_with_no_e.append(word)
    # ''.join() will returns all the elements of array concatenated
    # len() will count the length
    print(len(''.join(words_with_no_e)))

它将不带
e
in的所有单词附加到每行的新列表中,然后连接所有单词,然后打印其长度

如果你不明白这个问题,我愿意解释更多我只是想自己学习grok,但我遇到了一个问题,你在哪里提交新行?你能以合适的方式发布你的一些文件吗?0)对于每一行1)分割行,2)将计数设置为0,3)循环单词,4)如果单词不包含
e
则添加单词长度到
count
,5)打印
count
@Mehrdad pedramfar我刚刚编辑了它当你运行它时,你得到:“15 9 21 10 18 18 9 21 10 13 9 13 17 10 8 10 13 27 15 14 14 13 12 22 14”我们试图得到的答案是“4 5 17 6 16 7 5 5 13 9 8 10 2 10 2 10 27 15 2 4 0 3 22 14”如果我们按照@Jon Clement所说的,我认为我们最初将count设置为0,然后像count+=len(单词)那样做每次??但我都没有得到正确的答案,否则我可能会对Jon说的话感到困惑。哇!太好了!所以append方法将所有单词添加到了一起?@D.Ronald否append将把单词添加到新列表中,
'.join()
将它们连接起来。
for line in open("textname.txt"):
    line_strip = line.strip()
    line_strip_split = line_strip.split()
    words_with_no_e = []
    for word in line_strip_split:
        if "e" not in word:
            # Adding words without e to a new list
            words_with_no_e.append(word)
    # ''.join() will returns all the elements of array concatenated
    # len() will count the length
    print(len(''.join(words_with_no_e)))