def noalpha(s):
noa = ''
for c in s:
if not (c in noa or c.isalpha()):
noa += c
return noa
def flines(t, ww):
s=noalpha(t)
lines=t.lower().splitlines()
lst=[]
for i in range(len(lines)):
for caratteri in s:
lines[i]=lines[i].replace(caratteri, ' ')
wrdst=lines[i].split()
l= 'Line ' +str(i)+': '
False
for k in ww:
k=k.lower()
num=wrdst.count(k)
if num>0:
l+='"'+ str(k) + '"=' + str(num)+' '
True
if True:
lst+=[l]
return lst
有人可以向我解释我如何修改输出以便不显示空行?运行程序后得到的输出是:
['Line 0: "to"=1 ', 'Line 1: "the"=1 ', 'Line 2: "the"=1 ', 'Line 3: "to"=1 ', 'Line 4: "so"=2 ', 'Line 5: ', 'Line 6: ', 'Line 7: "to"=1 "the"=1 ', 'Line 8: "to"=1 "the"=2 ', 'Line 9: ', 'Line 10: ', 'Line 11: "to"=1 "the"=1 ', 'Line 12: ', 'Line 13: ', 'Line 14: "so"=1 ', 'Line 15: "to"=1 ', 'Line 16: ', 'Line 17: ', 'Line 18: "to"=1 "the"=2 ', 'Line 19: "the"=1 ', 'Line 20: "the"=4 ', 'Line 21: ', 'Line 22: ', 'Line 23: ', 'Line 24: ', 'Line 25: ', 'Line 26: ', 'Line 27: "the"=1 ', 'Line 28: ', 'Line 29: ', 'Line 30: "the"=1 ', 'Line 31: ']
答案 0 :(得分:0)
虽然这段代码并不适合你想做的事情,但你需要更改这些行
if num>0:
l+='"'+ str(k) + '"=' + str(num)+' '
True
if True:
lst+=[l]
如果您将其更改为
if num>0:
l+='"'+ str(k) + '"=' + str(num)+' '
flag = True
if flag:
lst+=[l]
然后如果你在for循环的开头重新初始化flag = False,它应该产生你想要的结果。通过执行if True,你要说的是总是附加到列表vs当那里有实际的东西时