简体   繁体   中英

Is there a way to identify if a word has the same letters next to each other?

I'm trying to create a function in python does specific functions with a list of words in a text document. All the other functions work so it is not a problem with the word document. This function i'm trying to create looks through each word on a word document and tells if there is two of the same letter next to each other in it. It always says there is 0 letters touching in the document.

I've tried this but just cannot for the life of me see why it is not working, at the part of

if word[a] == word[a+1:]: the variable a is 0, when it should be a letter of the word

def sameLettersTouchingFn(wordDocument):

    sameLettersTouchingCount = 0

    for word in wordDocument:

        for a in range(len(word)-1): #for every letter in the word

            if word[a] == word[a+1:]: #if letter is same as one next to it

                sameLettersTouchingCount +=1 # count goes plus one

        if sameLettersTouchingCount == 1: # if it has two letters touching

            print(word, "Has two of the same letter touching") #prints it has two letters touching


    print ("There is", sameLettersTouchingCount, "words with letters touching")

My expected results is it to print the words with the same letter touching in it and print how many words have the same letter touching. It doesn't say any words have the same letter touching and says 0 words have the same letters touching

if word[a] == word[a+1:]:

Should be

if word[a] == word[a+1]:

The first one is the rest of the word not the letter

You can use zip() and any() to check if duplicates arise:

sentences = ["this has not",
             "seems we got at least one", 
             "peers will see good things"]


for s in sentences: 
    cnt = 0
    for word in s.split():
        if any(a==b for a,b in zip(word,word[1:])):
            print (f"- '{word}' has same letter twice")
            cnt += 1
    if cnt:
        print(f"{cnt} word(s) with duplicate letters in '{s}'\n") 
    else: 
        print(f"No dupes in '{s}'\n")

Output:

No dupes in 'this has not'

- 'seems' has same letter twice
1 word(s) with duplicate letters in 'seems we got at least one'

- 'peers' has same letter twice
- 'will' has same letter twice
- 'see' has same letter twice
- 'good' has same letter twice
4 word(s) with duplicate letters in 'peers will see good things'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM