如何在文本文件中返回x元音量

时间:2015-05-23 06:05:19

标签: python string doctest

该函数采用文件名和x(用于返回文件名中的前2或4个元音)。我写的代码返回元音,但我不确定它返回的是什么。代码应该通过doctest。我还在努力解决这个问题,但如果有人对我做错了什么有任何建议,我将非常感激,因为我对python仍然相对较新。

文件名的内容是:("我有一堆红玫瑰")

def return_vowels(filename, x):
    """
    >>> return_vowels("roses.txt", 2)
    'Ia' #returns the first two vowels in the text
    >>> return_vowels("roses.txt", 3)
    'Iae'#returns the first three vowels in the text
    """
    files = open(filename)
    text_file = files.read()
    consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"#do not want consonants
    s_with_vowels = ""
    index = 0
    while index < x:
        for letter in read_files:
            if letter not in consonants:
                s_with_vowels += letter
        return s_with_vowels

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

3 个答案:

答案 0 :(得分:0)

首先,您不需要定义嵌套的whilefor循环,您只需要遍历该行并在每个单词处检查它是辅音还是元音?

如果它是一个元音,那么你只需增加计数,在迭代结束时,你检查计数是否超过了传递的值x

要记住的其他事情是你用辅音检查这个词,辅音错过了许多字符,如数字,特殊字符,空格等。所有这些都被算作元音。因此,最好检查一下元音串以克服这个缺点。

def count_vovels(filename, x):
    """
    >>> return_vowels("roses.txt", 2)
    'Ia' #returns the first two vowels in the text
    >>> return_vowels("roses.txt", 3)
    'Iae'#returns the first three vowels in the text
    """
    files = open(filename, "r")
    text_file = files.read()
    #consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"#do not want consonants
    vowels = "aeiou"
    s_with_vowels = ""
    index = 0
    #while index < x:
    for letter in text_file:
        if letter.lower() in vowels:
            s_with_vowels += letter
            index+=1
        if index >=x:
            break
    files.close()
    return s_with_vowels

print count_vovels("sample.txt", 2)
>>> Ia
print count_vovels("sample.txt", 3)
>>> Iae
print count_vovels("sample.txt", 4)
>>> Iaea

答案 1 :(得分:0)

根据我上面的评论,我修改了你的代码。我还做了一些其他更改,所有这些更改都标有以####

开头的评论
#### x??  Will you remember what X means when you come back to the code in 6b months time?
#### def return_vowels(filename, x):
def return_vowels(filename, numberOfVowelsToFind):

    #### I had problems with your comments in the doctest expected output (doctest expected them)
    """
    >>> return_vowels("roses.txt", 2)
    'Ia'

    >>> return_vowels("roses.txt", 3)
    'Iae'
    """

    #### slightly better name
    textFile = open(filename)
    fileBody = textFile.read()

    #### make your check inclusory, not exclusory.
    #### what if your file contained "I have a bunch of red roses"? 2 would be seen as a vowel
    #### consonants = "BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz"#do not want consonants
    vowels = 'AEIOU'

    #### use a slightly more meaningful variable name
    #### s_with_vowels = ""
    firstVowelsFound = ""

    index = 0
    while index < numberOfVowelsToFind:
        for letter in fileBody:
            if letter.upper() in vowels:
                firstVowelsFound += letter

            #### You need this check to know when you are done
            if len(firstVowelsFound) == numberOfVowelsToFind:
                return firstVowelsFound

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

Gratz使用doctest,顺便说一下。这是以上代码的输出:

  

E:\编码\的Python \的Python \ python.exe
  C:/ Users / me / PycharmProjects / untitled / vowels roses.txt尝试:
      return_vowels(&#34; roses.txt&#34;,2)期待:
      &#39; IA&#39;好的尝试:
      return_vowels(&#34; roses.txt&#34;,3)期待:
      &#39; IAE&#39;确定1项没有测试:
      主要 1个项目通过了所有测试:2个项目在主要 .return_vowels中进行2项测试。 2通过,0失败。测试通过了。

     

处理完成,退出代码为0

答案 2 :(得分:0)

这可以按预期工作:

def find_vowels(file_name, limit):
    """
    >>> # returns the first two vowels in the text
    >>> find_vowels("roses.txt", 2)
    'Ia'
    >>> # returns the first two vowels in the text
    >>> find_vowels("roses.txt", 3)
    'Iae'
    """
    count = 0
    res = []
    vowels = set('aeiuoAEIOU')
    with open(file_name) as fobj:
        for line in fobj:
            for c in line:
                if c in vowels:
                    count += 1
                    res.append(c)
                if count >= limit:
                    break
    return ''.join(res)

if __name__=="__main__":
    import doctest
    doctest.testmod(verbose=True)

并通过测试:

Trying:
    find_vowels("roses.txt", 2)
Expecting:
    'Ia'
ok
Trying:
    find_vowels("roses.txt", 3)
Expecting:
    'Iae'
ok
1 items had no tests:
    __main__
1 items passed all tests:
   2 tests in __main__.find_vowels
2 tests in 2 items.
2 passed and 0 failed.
Test passed.    

一些事情。

  1. 我使用set元音vowels = set('aeiuoAEIOU')
    检查集合中的成员资格比列表中的成员资格要快。

  2. 我使用列表来保存找到的元音res = []。 添加到字符串s +=时,它被认为是一个 由于可能长时间运行而导致的反模式 与其他实现,如PyPy。这没关系 根本就是你的榜样。但是编写好的代码不会受到伤害。

  3. 我使用with语句打开文件。 Python会 一旦我回到“与```&#39; .join(res)的水平,就把它关闭。

  4. 我使用for循环遍历文件的所有行。 一次在线使用可以使用 非常大的文件。

  5. 我没有使用while来检查元音的限制 而是一个counter和一个for循环,显式递增。 当到达文件末尾时,for循环终止。 如果尚未找到限制,while可能永远存在。

  6. ''.join(res)会从结果列表中创建一个字符串。