我的代码有问题。我有一个名为 .csv 的文件test.csv,其中包含 3 个句子。我想在读完第一句单词的长度后将长度的计数恢复为 0。with open("test.csv") as e: text = e.read()newtext = text.split()words = ''startindex = ''lastIndex = '' if words is not ".": for words in newtext: startIndex = text.rfind(words) lastIndex = startIndex + (len(words)) first_index = str(startIndex) last_index = str(lastIndex) print('(' + first_index + ',' + last_index + ')' + words) #The output would be #The output that i wanted #(36,38)My #(0,2)My #(39,43)name #(3,7)name #(44,46)is #(8,10)is #(18,21)bob #(11,14)bob #(51,52). #(15.16). #(18,21)bob #(0,3)bob #(44,46)is #(4,6)is #(25,27)my #(7,9)my #(39,43)name #(10,14)name #(51,52). #(15,16). #(36,38)My and so on... #(39,43)name #(44,46)is #(47,50)lob #(51,52).由于单词的重复覆盖。我希望它在 ('My name is bob.') 句子之后,单词计数将回到 0。在 test.csv 文件中:My name is bob .bob is my name . My name is lob .
1 回答
陪伴而非守候
TA贡献1757条经验 获得超8个赞
这就是我将如何解决这个问题:
with open("test.csv") as e:
text = e.read()
newtext = text.split()
words = ''
currCount = 0
for words in newtext:
toAdd = len(words)
print "("+str(currCount)+","+str(currCount+toAdd)+")"+ words
currCount+= toAdd+1
if words is ".":
currCount = 0
输出符合要求
> (0,2)My
> (3,7)name
> (8,10)is
> (11,14)bob
> (15,16).
> (0,3)bob
> (4,6)is
> (7,9)my
> (10,14)name
> (15,16).
> (0,2)My
> (3,7)name
> (8,10)is
> (11,14)lob
> (15,16).
添加回答
举报
0/150
提交
取消