如何设置 for 循环以附加任何带有标点符号的单词作为字典中具有空值的键

How to set up a for loop to append any word with punctuation with as a key with an empty value in a dictionary

我正在尝试使用代码开发一个马尔可夫链,它将从一个字符串中创建随机句子。我已经拆分了字符串并正在评估它。我当前的代码是:


#Your code here
string = '''how much wood could a woodchuck chuck
if a woodchuck could chuck wood?
as much wood as a woodchuck could chuck
if a woodchuck could chuck wood.'''
st_dict={}

for i in range(0, len(words)-1):
  #print(words)
  word=words[i]
  next_word=words[i+1]
  if word in ['.','?']:
    st_dict[word]=[]
  elif word in st_dict:
    st_dict[word].append(next_word)
  else:
    st_dict[word]=[next_word]
st_dict[words[-1]]=[]
print(st_dict)

但是,任何包含标点符号的单词都应该只有一个空列表作为其值。但是,我无法让它工作。我试过了: word not in ['.','?'... etc] 除了上面的 if 语句,但是字符串中间有标点符号的单词仍然附加下一个单词作为值。我该如何防止这种情况?

谢谢。

word in ['.','?'] 仅当 word 恰好 '.'恰好 '?'.

你想要相反的:'.' in word or '?' in word.

如果你有标点符号列表,那么你应该使用 any:

punctuation = ".?"
any(punct in word for punct in punctuation)