python - 有没有办法识别一个单词是否有相同的字母相邻?
问题描述
我正在尝试在 python 中创建一个函数,它使用文本文档中的单词列表来执行特定的函数。所有其他功能都可以正常工作,因此 word 文档没有问题。我正在尝试创建的此功能通过 word 文档上的每个单词进行查看,并判断其中是否有两个相同的字母彼此相邻。它总是说文档中有0个字母接触。
我已经尝试过了,但我一生都无法理解为什么它不起作用,在
if word[a] == word[a+1:]:变量a为0,此时应该是单词的字母
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")
我的预期结果是打印带有相同字母的单词,并打印有多少单词有相同的字母。它没有说任何单词具有相同的字母感人,并说 0 个单词具有相同的字母感人
解决方案
if word[a] == word[a+1:]:
应该
if word[a] == word[a+1]:
第一个是单词的其余部分而不是字母
推荐阅读
- excel - 如何在数据验证的下拉列表中添加更多约 500 条记录?
- match - 带有 MATCH 和 OFFSET 的 VLOOKUP
- spring-boot - 如何将 elastic-apm-agent.jar 添加到 PCF?
- bash - 仅为 Mac 创建和运行 go build?
- c# - C# 简单的 SSH 连接和向 linux 主机发送命令
- c++ - 为什么不需要对指针使用这个关键字?
- git - 如何正确使用 .gitignore?
- python - 检测图像中的相似对象
- spring - 如何自动刷新配置客户端?
- google-drive-api - 刷新访问令牌时出现未经授权的客户端错误