python - 同时迭代字符串的元素
问题描述
我有一本字典,其中包含以 the 为键的句子,book
以及page
它来自的句子:
# 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
defaultdict(<type 'dict'>, {'A': {50: 'ALLFROMDIFFERENTBOOKS', 1021: 'MOSLTYTHESAMELENGTHSS'}, 'P': {41: 'ANDHEREISONEMOREEXAMP'}, 'C': {111: 'ANDFROMDIFFERENTPAGES'}, 'M': {121: 'BUTSOMEWILLBABITSHORT', 12: 'THISISASENTANCE'}})
我还有一个元音池存储为字典,因此每个元音以 10 开头:
vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10)
我想遍历每个句子 ( sentence[0][0]. sentence[n][0], ...
) 的相同元素,并且每次我看到元音 ( A
, E
, I
, O
, or ) 时都会从字典U
中减少该元音的数量。vowels
一旦元音池命中,0
我在句子中返回 ,letter
并打破循环。position
sentence
from collections import defaultdict
import random
def wordStopper(sentences):
random.shuffle(sentences)
vowels = dict.fromkeys(['A', 'E', 'I', 'O', 'U'], 10)
for i in range(len(sentences[1])):
for s in sentences:
try:
l = s[i:i + 1]
except IndexError:
continue
if l in vowels:
vowels[l] -= 1
print("Pos: %s, Letter: %s, Sentence: %s" % (i, l, s))
print("As = %s, Es = %s, Is = %s, Os = %s, Us = %s" %(vowels['A'], vowels['E'], vowels['I'], vowels['O'], vowels['U']))
if vowels[l] == 0:
return(l, i, s)
letter, location, sentence = wordStopper(sentences)
print("Vowel %s exhausted here %s in sentence: %s" % (letter, location, sentence))
将列表打乱很重要sentences
(并且我遍历0
所有句子中的 element ,然后遍历 element 1
),这样我就不会偏向列表中的较早条目sentences
。
book
这可以按我的预期工作,但我现在想检索page
存储sentence
在coordinates
.
我可以通过迭代coordinates
并找到sentence
从返回的内容来粗略地实现这一点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))
然而,这让我觉得这是实现这一目标的一种相当糟糕的方式。
通常,我可能会迭代coordinates
句子之前的键,但我看不到这样做的方法,因此它不会使结果偏向于迭代的第一个键。
非常欢迎任何建议 注意:这是玩具示例,所以我不打算使用任何语料库解析工具
解决方案
我认为你需要的是一个更好的数据结构,它可以让你从句子中检索书籍/页面。有许多可能的设计。这就是我要做的:
首先,创建一个包含句子及其书/页的数据结构:
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]
此时,初始化 sentence_with_meta 字段 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 方法中,使用 sentence_with_meta 数组,方法如下:
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]
还有许多其他设计也可以使用。
推荐阅读
- php - Laravel Auth 返回不同的数据
- operating-system - 操作系统线程和锁定问题
- apache-flink - Flink:关于 flink 检查点和保存点的查询
- intellij-idea - Intellij 的 Angular 和 Type 脚本支持插件
- c# - Stripe Payment:System.Net.WebException:请求被中止:无法创建 SSL/TLS 安全通道
- python - 为什么在相同的环境下结果会不同?
- bitbucket - 在 Bitbucket 上为多个存储库托管静态网站
- python - 如何从 python OpenCV Thresholding 获得更好的结果?
- swift - Swift .ics 文件未在 swift 4 中添加到日历中
- java - 如何确定 Java Intstream 中的整数是否为 3x+1 形式?