首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果“%s”中的最后一个单词以辅音开头,则会说index超出范围。我如何改变程序来改变这一点呢?

如果“%s”中的最后一个单词以辅音开头,则会说index超出范围。我如何改变程序来改变这一点呢?
EN

Stack Overflow用户
提问于 2015-04-13 16:46:23
回答 1查看 108关注 0票数 0
代码语言:javascript
复制
def to_pig_latin(s):
    j = 0 # points to first character in word  
    i = 0
    new_sentence_1 = '' # variable to store strings being changed
    vowel_position = 0 # show the position of the first vowel
    number_of_words = 0
    number_of_spaces = s.count(" ") 
    number_of_words = number_of_spaces + 1

    space_position = s.find(" ") # find the position of the first space
    sent = s[:space_position] # slice the first word of the sentence
    old_sent = s[len(sent)+1:] # stores the old sentence without the first word of s

    while number_of_spaces >= 0:
        if sent[j] in ["a", "e", "i", "o", "u"]: # checks if first character is a vowel
            new_sentence = sent + "way" # adds 'way' to the first word
            new_sentence_1 = new_sentence_1 + ' ' + new_sentence # adds the words

        else: # if first character is not equal to a vowel
            for i in range(len(sent)):
                # check to see if first character in s is a vowel
                if s[i] == 'a': 
                    break
                if s[i] == 'e':
                    break
                if s[i] == 'i':
                    break
                if s[i] == 'o':
                    break
                if s[i] == 'u':
                    break

            vowel_position = i # takes position of first vowel reached in word
            consonant_sequence = sent[:vowel_position] # stores all the consonants up to the first vowel, but not the first vowel
            sent = sent[vowel_position:] # slices the word from the first vowel to the end
            new_sentence = sent + 'a' + consonant_sequence + 'ay' # adds strings
            new_sentence_1 = new_sentence_1 + ' ' + new_sentence # adds the words

        s = old_sent # takes the value of old_sent
        space_position = s.find(" ") # find the position of the first space

我如何更改下面的部分,以便即使在s中有一个单词也能进行检查?或者如果字符串s中的最后一个单词以一个以一个或多个辅音开头的单词结尾?

代码语言:javascript
复制
    if space_position == -1:
        space_position = len(s)
        sent = s[:space_position]
        if sent[j] in ["a", "e", "i", "o", "u"]:
            new_sentence = sent + "way"
            new_sentence_1 = new_sentence_1 + ' ' + new_sentence
            break
        else:
            for i in range(len(sent)):
                if s[i] == 'a':
                    break
                if s[i] == 'e':
                    break
                if s[i] == 'i':
                    break
                if s[i] == 'o':
                    break
                if s[i] == 'u':
                    break

        vowel_position = i
        consonant_sequence = sent[:vowel_position]
        sent = sent[vowel_position:]
        new_sentence = sent + 'a' + consonant_sequence + 'ay'
        new_sentence_1 = new_sentence_1 + ' ' + new_sentence            


    sent = s[:space_position]
    old_sent = s[len(sent)+1:]
    number_of_spaces = s.count(" ")
    number_of_words = number_of_spaces + 1

return new_sentence_1[1:]

英语/小语种翻译器测试程序:

代码语言:javascript
复制
import piglatin

choice = input ("(E)nglish or (P)ig Latin?\n")
action = choice[:1]
if action == 'E':
    s = input("Enter an English sentence:\n")
    new_s = piglatin.to_pig_latin(s)
    print("Pig-Latin:")
    print(new_s)
elif action =='P':
    s = input("Enter a Pig Latin sentence:\n")
    new_s = piglatin.to_english(s)
    print("English:")
    print(new_s)

输出:

代码语言:javascript
复制
(E)nglish or (P)ig Latin? E
Enter an English sentence: My friend next to me is wearing a shoe
Traceback (most recent call last):  
  File "/Applications/Wing101.app/Contents/Resources/src/debug/tserver/_sandbox.py",
   line 9, in <module>
  File "/Users/azhar/Desktop/Computer Science/Assignments/Assignment 4 (Functions & Strings)/piglatin.py", line 46, in to_pig_latin
    if sent[j] in ["a", "e", "i", "o", "u"]: # checks if first value in j is equal to a vowel
builtins.IndexError: string index out of range
EN

回答 1

Stack Overflow用户

发布于 2015-04-13 17:32:21

我认为,比起修复特定的问题,简化代码会更容易。

首先,您可以使用s.split()拆分句子,这将为您提供一个以空格分隔的单词列表。其次,可以使用s.find()查找给定字符串的索引。第三,可以使用' '.join(sen)通过空格连接字符串列表。

因此,使用这些,您的代码简化为(我还添加了大小写处理):

代码语言:javascript
复制
def to_pig_latin(sen):
    senlst = sen.lower().split()  # split into list of words
    for i, word in enumerate(senlst):
        if word[0] in 'aeiou':
            senlst[i] += 'way'
        else:
            for vow in 'aeiou':
                ind = word.find(vow)
                if ind >= 0:
                    break
            if ind < 0: # no vowel in word
                continue
            senlst[i] = word[ind:]+'a'+word[:ind]
    newsen = ' '.join(senlst)  # combine list of words into sentence
    if sen[0].isupper():  # make capitalization like original
        newsen = newsen.capitalize()
    return newsen

然而,如果你真的想检查是否有一个单词,你可以做if s.strip():。这样做的目的是去掉前导或尾随空格。如果没有单词,则会留下一个空字符串。在python中,空字符串(或空列表或元组)被认为是False,因此您可以在if测试中使用它来对这种情况进行任何类型的处理。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29601257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档