【问题标题】:Three Sets of Doubles三组双打
【发布时间】:2021-01-04 16:20:17
【问题描述】:

我正在编写一个程序,其中给了我一个名为 words.txt 的文件。它包含每一个单词,并且开头为 “啊 啊啊 啊哈 啊啊啊啊 啊啊啊 . . 。” 使用该文件,我应该遍历它并找到所有具有三组双字母的单词。 (双字母是指连续有两个相同的字母,例如在 boot、kill 或 abyss。)三组双字母表示像委员会这样的词,有 1 组 (mm)、2 组、(tt) 和第三组,(ee)。然后程序必须显示所有找到的单词,以及找到的单词总数。我不允许导入模块或其他工具,我只能使用基本的 Python。任何帮助表示赞赏。


found_words = []
total = 0

for line in f:
    line = line.strip()
    letter_list = []
    
    for letter in line:
        letter_list.append(letter)

for letter in line:
    if letter_list[0] == letter_list[1]:
        found_words.append(line)
    else:
        del letter_list[0]
        
            

print(letter_list)

print(found_words) 
        


f.close()

【问题讨论】:

  • 嘿@Madison Han.Stackoverflow 不是代码编写服务。您应该自己尝试一下,显示您遇到的错误以及卡住的位置。实际上,我可以编写并给你整个代码,但这就是 stackoverflow 的工作方式。好的,将其添加到您的问题中,如 `````` 之类的反引号,我只是在写答案
  • 好的。我开始只把它写到一个双精度,但后来我得到了一个错误。
  • 欢迎堆栈溢出!请edit您的问题包括您的完整minimal reproducible example。代码在 cmets 中显示不好
  • 请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。我们应该能够复制和粘贴您的代码的连续块,执行该文件,并重现您的问题以及跟踪问题点的输出。

标签: python letter


【解决方案1】:

给你

f = open("words.txt")
found_words = []
words= f.read().split()
for word in words:
  consecutive =0
  lastLetter=""
  for letter in word: 
    if letter == lastLetter:
      consecutive+=1
      //If you want it that if three similar letters should count as 2 repeated, dont uncomment the next line. If you dont want 3 consecutive letters to count as 2 repeated, uncomment the next line
      //lastLetter=""
    lastLetter =letter
  if consecutive ==3:
   found_words.append(word)
print("WORDS:",found_words)
print("LENGTH:",len(found_words))    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多