检查抑扬格五步格?

2024-05-28 23:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点纠结于一个关于五步抑扬格的问题,但是因为它很长,我会尽量简化它。 所以我需要从一个文本文件中得到一些单词和它们的重音模式,看起来有点像这样:

if, 0
music,10
be,1
the,0
food,1
of,0
love,1
play,0
on,1
hello,01
world,1

从文件中,你可以假设不同的句子会有更多的单词。我试着从一个有多个句子的文本文件中获取句子,看看这个句子(忽略标点和大小写)是否是抑扬格五步格。

例如,如果文本文件包含以下内容:

If music be the food of love play on
hello world

第一个句子将像这样从重音词典中赋值:0101010101,第二个显然不是五进制(011)。我希望它只打印抑扬格五步格的句子。

对不起,如果这是一个复杂或混乱的问题。 这就是我目前所拥有的:

import string
dict = {};
sentence = open('sentences.txt')
stress = open('stress.txt')
for some in stress:
  word,number = some.split(',')
  dict[word] = number
for line in sentence:
  one = line.split()

Tags: ofthehelloworldplayfoodonmusic
3条回答

下面是完整代码的外观:

#!/usr/bin/env python3
def is_iambic_pentameter(words, word_stress_pattern):
    """Whether words are a line of iambic pentameter.

    word_stress_pattern is a callable that given a word returns
    its stress pattern
    """
    return ''.join(map(word_stress_pattern, words)) == '01'*5

# create 'word -> stress pattern' mapping, to implement word_stress_pattern(word)
with open('stress.txt') as stress_file:
    word_stress_pattern = dict(map(str.strip, line.split(','))
                               for line in stress_file).__getitem__

# print lines that use iambic pentameter
with open('sentences.txt') as file:
    for line in file:
        if is_iambic_pentameter(line.casefold().split(), word_stress_pattern):
            print(line, end='')

我不会认为抑扬格五步舞曲有那么明显的特点:为了配合节奏,有些词最后总是会变得有压力或没有压力。但无论如何。像这样的:

for line in sentences:
    words = line.split()
    stresspattern = ''.join([dict[word] for word in words])
    if stresspattern=='0101010101':
         print line

顺便说一句,通常把字典叫做dict是个坏主意,因为你隐藏了dict类型。

我认为你没有正确地建立你的压力字典。重要的是要记住在阅读时去掉行中的隐式\n字符,并且在逗号上拆分后去掉单词中的任何空白。从目前的情况来看,行if, 0将被拆分为['if', ' 0\n'],这不是您想要的。

因此,要创建压力字典,可以执行以下操作:

stress_dict = {}

with open('stress.txt', 'r') as f:
    for line in f:
        word_stress = line.strip().split(',')
        word = word_stress[0].strip().lower()
        stress = word_stress[1].strip()
        stress_dict[word] = stress

对于实际的检查,@khelwood的答案是一个很好的方法,但是我会格外小心地处理您在行中读到的\n字符,并确保行中的所有字符都是小写的(就像在您的字典中一样)。

定义一个函数is_iambic_pentameter来检查一个句子是否是抑扬格五步格(返回True/False),然后检查sentences.txt中的每一行:

def is_iambic_pentameter(line):
    line_stresses = [stress_dict[word] for word in line.split()]
    line_stresses = ''.join(line_stresses)
    return line_stresses == '0101010101'

with open('sentences.txt', 'r') as f:
    for line in f:
        line = line.rstrip()
        line = line.lower()
        if is_iambic_pentameter(line):
            print line

另外,您可能对NLTK感兴趣,这是一个Python的自然语言处理库。一些互联网搜索发现,人们已经编写了俳句生成器和其他脚本,以评估诗体形式使用的图书馆。

相关问题 更多 >

    热门问题