阅读句子中每个单词的长度后如何恢复为0

时间:2019-02-07 19:06:42

标签: python

我的代码有问题。我有一个名为test.csv的.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).

由于单词的重复,其被覆盖。我希望它出现在(“我的名字叫鲍勃”)句子后面,字数重新回到0。

在test.csv文件内部:

My name is bob .

bob is my name . 

My name is lob .

1 个答案:

答案 0 :(得分:0)

这就是我要解决的问题的方式:

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).