Python 没有名为';msvcrt';

Python 没有名为';msvcrt';,python,python-3.x,macos,msvcrt,Python,Python 3.x,Macos,Msvcrt,我被困在这里(下图),需要通过它才能阅读我的文本。我还有text.txt文件。程序本身不会使用python 2运行。python 2在这里给了我一个错误:print(最后的建议,end='',flush=True) train_data='text.txt' 第一个可能的单词={} 第二个可能的单词={} 转换={} def expandDict(字典、键、值): 如果关键字不在字典中: 字典[键]=[] 字典[key]。追加(值) def get_next_概率(给定列表):#返回字典 概率_

我被困在这里(下图),需要通过它才能阅读我的文本。我还有text.txt文件。程序本身不会使用python 2运行。python 2在这里给了我一个错误:
print(最后的建议,end='',flush=True)

train_data='text.txt'
第一个可能的单词={}
第二个可能的单词={}
转换={}
def expandDict(字典、键、值):
如果关键字不在字典中:
字典[键]=[]
字典[key]。追加(值)
def get_next_概率(给定列表):#返回字典
概率_dict={}
给定列表长度=len(给定列表)
对于给定_列表中的项目:
概率dict[item]=概率dict.get(item,0)+1
对于键,概率项()中的值:
概率dict[键]=值/给定列表长度
返回概率
def trainMarkovModel():
对于开放线路(列车数据):
令牌=line.rstrip().lower().split()
令牌长度=len(令牌)
对于范围内的i(令牌长度):
令牌=令牌[i]
如果i==0:
第一个可能的单词[token]=第一个可能的单词。get(token,0)+1
其他:
prev_令牌=令牌[i-1]
如果i==tokens\u length-1:
expandDict(转换,(上一个令牌,令牌),“结束”)
如果i==1:
expandDict(第二个可能的字、上一个标记、标记)
其他:
prev_prev_token=代币[i-2]
expandDict(转换,(上下上下令牌,上下令牌),令牌)
第一个可能的单词总数=总和(第一个可能的单词.values())
对于键,第一个单词中的值。items():
第一个可能的单词[关键字]=值/第一个可能的单词总数
对于上一个单词,请在第二个单词中列出下一个单词。items():
第二个可能单词[上一个单词]=获取下一个单词的概率(下一个单词列表)
对于单词对,在transitions.items()中的下一个单词列表:
转换[单词对]=获取下一个单词的概率(下一个单词列表)
定义下一个单词(tpl):
#打印(过渡)
if(type(tpl)==str):#它是字符串的第一个字。。从第二个单词返回
d=第二个可能的单词。获取(tpl)
如果(d)不是无:
返回列表(d.keys())
if(type(tpl)=tuple):#传入词是两个词的组合。。现在根据转换查找下一个单词
d=转换。获取(tpl)
如果(d==无):
返回[]
返回列表(d.keys())
返回无#输入错误。。一无所获
trainMarkovModel()#生成第一个、第二个单词列表和转换
##########下面是演示代码################
打印(“用法:开始键入..程序将建议单词。按tab键选择第一个建议或继续键入\n”)
导入msvcrt#使用mscvrt从用户实时获取字符,无需按enter键
c=''
发送=“”
最后的建议=[]
while(c!=b'\r'):#当用户输入时停止
如果(c!=b'\t'):#如果前一个字符是tab,则自动完成后不要等待用户输入。。只是提出建议
c=msvcrt.getch()
其他:
c=b“
如果(c!=b'\t'):#不打印选项卡等
打印(str(c.decode('utf-8')),end='',flush=True)
sent=sent+str(c.decode('utf-8'))#在空格上创建单词
如果(c==b“”):
tkns=sent.split()
if(len(tkns)<2):#只遇到第一个空格
最后一个建议=下一个单词(tkns[0].lower())
打印(最后建议,结束='',刷新=真)
否则:#发送一个元组
最后一个建议=下一个单词((tkns[-2].lower(),tkns[-1].lower())
打印(最后建议,结束='',刷新=真)
如果(c==b'\t'和len(最后建议)>0:#在选项卡上打印最后建议
打印(最后建议[0],结束='',刷新=真)
已发送=已发送+“”+上次建议[0]
我正在使用Mac并在可视代码中运行此操作,这是我得到的错误:

baylarbayramov@Baylars-MacBook Pro markov预测下一个单词master%python3-u“markov_nextwordpred.py”
用法:开始键入。。程序将建议使用单词。按tab键选择第一个建议或继续键入
回溯(最近一次呼叫最后一次):
文件“markov_nextwordpred.py”,第69行,在
导入msvcrt
ModuleNotFoundError:没有名为“msvcrt”的模块

此模块仅适用于windows,您似乎在mac上运行此模块。在这里试试其他的解决方案:(虽然不是很令人满意)还要注意,
print
已经从Python2中的语句更改为Python3中的函数。要在Python2中使用函数形式,请在代码的开头添加一个来自_future _导入print_函数的
。看见
train_data = 'text.txt'

first_possible_words = {}
second_possible_words = {}
transitions = {}

def expandDict(dictionary, key, value):
    if key not in dictionary:
        dictionary[key] = []
    dictionary[key].append(value)

def get_next_probability(given_list):   #returns dictionary
    probability_dict = {}
    given_list_length = len(given_list)
    for item in given_list:
        probability_dict[item] = probability_dict.get(item, 0) + 1
    for key, value in probability_dict.items():
        probability_dict[key] = value / given_list_length
    return probability_dict

def trainMarkovModel():
    for line in open(train_data):
        tokens = line.rstrip().lower().split()
        tokens_length = len(tokens)
        for i in range(tokens_length):
            token = tokens[i]
            if i == 0:
                first_possible_words[token] = first_possible_words.get(token, 0) + 1
            else:
                prev_token = tokens[i - 1]
                if i == tokens_length - 1:
                    expandDict(transitions, (prev_token, token), 'END')
                if i == 1:
                    expandDict(second_possible_words, prev_token, token)
                else:
                    prev_prev_token = tokens[i - 2]
                    expandDict(transitions, (prev_prev_token, prev_token), token)

    first_possible_words_total = sum(first_possible_words.values())
    for key, value in first_possible_words.items():
        first_possible_words[key] = value / first_possible_words_total

    for prev_word, next_word_list in second_possible_words.items():
        second_possible_words[prev_word] = get_next_probability(next_word_list)

    for word_pair, next_word_list in transitions.items():
        transitions[word_pair] = get_next_probability(next_word_list)


def next_word(tpl):
    #print(transitions)
    if(type(tpl) == str):   #it is first word of string.. return from second word
        d = second_possible_words.get(tpl)
        if (d is not None):
            return list(d.keys())
    if(type(tpl) == tuple): #incoming words are combination of two words.. find next word now based on transitions
        d = transitions.get(tpl)
        if(d == None):
            return []
        return list(d.keys())
    return None #wrong input.. return nothing


trainMarkovModel()  #generate first, second words list and transitions

########## demo code below ################
print("Usage: start typing.. program will suggest words. Press tab to chose the first suggestion or keep typing\n")

import msvcrt   #use of mscvrt to get character from user on real time without pressing enter
c=''
sent=''
last_suggestion=[]
while(c != b'\r'):  #stop when user preses enter
    if(c != b'\t'): #if previous character was tab, then after autocompletion dont wait for user inpput.. just show suggestions
        c=msvcrt.getch()
    else:
        c = b' '
    if(c != b'\t'): #dont print tab etc
        print(str(c.decode('utf-8')), end=' ', flush=True)
    sent = sent + str(c.decode('utf-8'))  #create word on space
    if(c == b' '):
        tkns = sent.split()
        if(len(tkns) < 2):  #only first space encountered yet
            last_suggestion = next_word(tkns[0].lower())
            print(last_suggestion, end='  ', flush=True)
        else: #send a tuple
            last_suggestion = next_word((tkns[-2].lower(), tkns[-1].lower()))
            print(last_suggestion, end='  ', flush=True)
    if (c == b'\t' and len(last_suggestion) > 0):   #print last suggestion on tab
        print(last_suggestion[0], end='  ', flush=True)
        sent = sent + " " + last_suggestion[0]