简体   繁体   English

CS50 第 6 周 Python 可读性

[英]CS50 Week 6 Python Readability

The problem set number 6 in cs50 requires to rebuild the Readability project from week 2 in Python cs50 中的问题集 6 需要从 Python 的第 2 周开始重建可读性项目
But there is a problem I haven't encountered first when writing the code in C但是有一个问题我在C中写代码的时候没有先遇到
The programm uses for loop for each letter in input to check if its a period, exclamation point, or question mark which all indicate the end of a sentence程序对输入中的每个字母使用 for 循环来检查它是否都是句号、感叹号或问号,它们都表示句子的结尾
But the input that check50 throws at the program has multiple periods back to back each of which count as its own sentence但是 check50 向程序抛出的输入有多个背靠背的句点,每个句点都算作自己的句子
So the question is:所以问题是:
How can I improve this sentence counting function to only concider one of periods in case it encounters them back to back?我如何改进这句话计数 function 只考虑其中一个时期,以防它背靠背遇到它们? Should I for example add a condition that sees next symbol in a for loop and if its also a period it just ignores it?例如,我是否应该添加一个在 for 循环中看到下一个符号的条件,如果它也是一个句点,它只是忽略它?

def countSentences(input):
    counterS = 0
    for symbol in input:
        if symbol in ['.', '!', '?']:
            counterS += 1
    return counterS

You can save the previous symbol in another variable.您可以将前一个符号保存在另一个变量中。 Then if it's the same as the current symbol, don't count it.那么如果和当前符号相同,就不要算了。

def countSentences(input):
    counterS = 0
    previous_symbol = None
    for symbol in input:
        if symbol in ['.', '!', '?']:
            if previous_symbol != symbol:
                counterS += 1
        previous_symbol = symbol
    return counterS

If you only care about counting the sentences and not tracking which punctuation was used, you can use re.sub to squash duplicate punctuation into a single period ( . ).如果您只关心计算句子而不是跟踪使用了哪个标点符号,您可以使用re.sub将重复的标点符号压缩为单个句点 ( . )。 The function would look like the following function 如下所示

Documentation here文档在这里

import re

def countSentences(input):
  counterS = 0
  for symbol in re.sub('[.!?]+', '.', input):
    if symbol in ['.', '!', '?']:
      counterS += 1
  return counterS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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