Python 同时迭代字符串的元素
我有一本字典,里面的句子是由Python 同时迭代字符串的元素,python,Python,我有一本字典,里面的句子是由书和页面输入的: # lists to build dictionary - for reproducibility pages = [12, 41, 50, 111, 1021, 121] bookCodes = ['M', 'P', 'A', 'C', 'A', 'M'] sentences = ['THISISASENTANCE', 'ANDHEREISONEMOREEXAMP', 'ALLFRO
书
和页面
输入的:
# lists to build dictionary - for reproducibility
pages = [12, 41, 50, 111, 1021, 121]
bookCodes = ['M', 'P', 'A', 'C', 'A', 'M']
sentences = ['THISISASENTANCE',
'ANDHEREISONEMOREEXAMP',
'ALLFROMDIFFERENTBOOKS',
'ANDFROMDIFFERENTPAGES',
'MOSLTYTHESAMELENGTHSS',
'BUTSOMEWILLBABITSHORT'
]
# Make dictionary
coordinates = defaultdict(dict)
for i in range(len(pages)):
book = bookCodes[i]
page = pages[i]
sentence = sentences[i]
coordinates[book][page] = sentence
print coordinates
重要的是,
句子
列表被洗牌(我在所有句子中迭代元素0
,然后迭代元素1
),这样我就不会偏向句子
列表中的早期条目
这和我预期的一样,但是我现在想检索书
和页面
编号,从中提取句子
,这些编号存储在坐标中
我可以通过迭代坐标
并找到从wordStopper
返回的句子
来大致实现这一点:
print coordinates
for book in coordinates.keys():
for page, s in coordinates[book].iteritems():
if s == sentence:
print("Book:%s, page: %s, position: %s, vowel: %s, sentence: %s" % (book, page, location, letter, sentence))
然而我觉得这是一个相当糟糕的实现方法
通常,我可能会在句子之前迭代坐标
的键,但我找不到这样做的方法,这样就不会使结果偏向迭代的第一个键
欢迎提出任何建议
注意:这是一个玩具示例,因此我不打算使用任何语料库解析工具我认为您需要的是更好的数据结构,它可以让您从句子中检索书籍/页面。有许多可能的设计。这就是我要做的:
首先,创建一个包含句子及其书籍/页面的数据结构:
class SentenceWithMeta(object):
def __init__(self, sentence):
self.sentence = sentence
self.book = None
self.page = None
然后,保持你所有的句子。例如:
sentences_with_meta = [SentenceWithMeta(sentence) for sentence in sentences]
此时,使用_元字段book和page字段初始化句子_:
# Make dictionary
sentences_with_meta = [SentenceWithMeta(sentence) for sentence in sentences]
for i in range(len(pages)):
book = bookCodes[i]
page = pages[i]
sentence_with_meta = sentences_with_meta[i]
sentence_with_meta.book = book
sentence_with_meta.page = page
最后,在wordStopper方法中,使用带有元数组的句子,方法如下:
def wordStopper(sentences):
random.shuffle(sentences_with_meta)
vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10)
for i in range(len(sentences[1])):
for swm in sentences_with_meta:
try:
l = swm.sentence[i:i + 1]
...
# the rest of the code is the same. You return swm, which has the book
# and page already in the structure.
侧节点:要从字符串中获取字母i,不需要使用slice。只需使用索引引用:
l = swm.sentence[i]
还有许多其他的设计也可以使用。我不知道你是否仍然可以访问句子
,页面
,和书籍代码
,但是你可以使用索引=句子。索引(句子)
,从那里开始工作你有平行列表,因此,句子
中的句子
索引将是页面
和书籍代码
中的正确索引。注意:index()
将只提供列表中第一个匹配项的索引。我不确定我是否理解您在这里所做的工作。您的对象中存储的书籍/页面信息在哪里(当您设置它时,None
)?富谷,在构建期间,我只放了一个。在我的示例代码中,我没有编写您命名为“makedictionary”的功能。你应该做你今天正在做的任何事情,但是把这一行替换为:坐标[book][page]=句子
def wordStopper(sentences):
random.shuffle(sentences_with_meta)
vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10)
for i in range(len(sentences[1])):
for swm in sentences_with_meta:
try:
l = swm.sentence[i:i + 1]
...
# the rest of the code is the same. You return swm, which has the book
# and page already in the structure.
l = swm.sentence[i]