Exemple #1
0
def CalculateCOS():
    print("请输入第一个向量坐标,x,y坐标用空格隔开,按Enter键完成:")
    p1 = input()
    tmp1 = p1.split()
    if isdigit(tmp1[0]) == False or isdigit(tmp1[1]) == False:
        print("输入非法,请重新输入!")
        return

    if isinstance(int(tmp1[0]), int) and isinstance(int(tmp1[1]), int):
        print("您输入的第一个向量为(" + p1.split()[0] + "," + p1.split()[1] + ")" +
              "\n" + "请按照同样的方式输入第二个向量坐标,按Enter键完成:")
        p2 = input()
        tmp2 = p2.split()
        if isdigit(tmp2[0]) == False or isdigit(tmp2[1]) == False:
            print("输入非法,请重新输入!")
            return
        if isinstance(int(tmp2[0]), int) and isinstance(int(tmp2[1]), int):
            print("您输入的第二个向量为(" + p2.split()[0] + "," + p2.split()[1] + ")")
            p1x = int(p1.split()[0])
            p1y = int(p1.split()[1])
            p2x = int(p2.split()[0])
            p2y = int(p2.split()[1])
            a = p1x * p2x + p1y * p2y
            b = sqrt((p1x**2) + (p1y**2))
            c = sqrt((p2x**2) + (p2y**2))
            cos = a / (b * c)
            print("您输入的两个向量的余玄值为%f:" % (cos))
            return
        pass
    return
Exemple #2
0
def is_decomp(r1, r2, operator):
    # if the two responses aren't in the same item, can't be decomposed
    #if item_check(r1, r2) == "N":
        #return False

    # must have operator in the potentially "decomposed" response
    if operator not in r2:
        return False

    decomp = "Maybe"
    decomp_len = 0

    # search for decomposition from r1 -> r2 (as in: R1 = 2 + 2, R2 = 1 + 1 + 2)
    # therefore, r2 cannot be shorter than r1
    if len(r2) < len(r1):
        return False

    for i in range(len(r1)):
        sub_exp = ""
        # start at i's position in j
        # if decomp found this will change
        for j in range(i, len(r2)):
            # potential for decomposition
            if (r2[j] != r1[i] and j == i) and ((j + 1 < len(r2) and r2[j + 1] == operator) or (j - 1 < len(r2) and r2[j - 1] == operator and r2[j + 1] != operator)):
                k = j
                while k < len(r2):
                    sub_exp += r2[k]
                    print(sub_exp)
                    
                    # do the stuffs
                    if isdigit(sub_exp[-1]):
                        if pd.eval(sub_exp) == int(r1[i]):
                            decomp_len += len(sub_exp)
                            decomp = "True"
                            break
                        elif (k == len(r2) - 1 or (isdigit(r2[k]) and r2[k + 1] != "+")) and decomp == "Maybe":
                            decomp = "False"
                            j += k - j
                            break
                        else:
                            decomp = "Maybe"     
                    k += 1
            if decomp == "True":
                break

            # These expressions don't match up, can't be decomposed
            if decomp == "False" and ((j == i and r2[j] != r1[i]) or (j == i + len(sub_exp))):
                return False
            # These expressions have at least one case of decomposition
            # but we need to make sure there are no other differences
            elif decomp == True and j == i + len(sub_exp):
                if r2[j] != r1[i]:
                    # the expressions have another difference
                    return False

    # The expressions only differ by one or more cases of decomposition, all good
    return True
Exemple #3
0
def get_operands(r, operator):
    # op_list: list of operands for either "*"" or "+""
    op_list = []

    for i in operator:
        if isdigit(i):
            op_list.append(i)
    
    return op_list
Exemple #4
0
    def creatWordDict(self):
        """
        creat self.word_dict && self.word_list according to self.infolist, select top 10% of the keywords
        :return: Null
        """
        temp_dict = {}
        word_num = 0
        for info_item in self.infolist:
            # print(info_item.title)
            # print(info_item.text)

            # info_weight 待调
            info_weight = info_item.attitudecount + 2 * info_item.commentcount
            # print(info_weight)
            keynum = math.ceil(len(info_item.title) / 5)
            keywords = analyse.extract_tags(info_item.title, topK=keynum)
            for word_item in keywords:
                if word_item in temp_dict:
                    temp_dict[word_item] += 5
                else:
                    temp_dict[word_item] = info_weight + 5

            text_list = re.split(',|。|?|!', info_item.text)
            for sentence in text_list:
                # print(sentence)
                keynum = math.ceil(len(sentence) / 10)
                keywords = analyse.extract_tags(sentence, topK=keynum)
                # print(keywords)
                for word_item in keywords:
                    if word_item in temp_dict:
                        temp_dict[word_item] += 1
                    else:
                        temp_dict[word_item] = 1

        word_temp_list = sorted(temp_dict.items(), key=lambda item: item[1], reverse=True)  # 出来后是列表形式
        topnum = math.ceil(len(word_temp_list) / 10)

        # creat self.word_dict
        i = 0
        while word_num < topnum:
            w = word_temp_list[i][0]
            if not isdigit(w) and w not in stopwords:
                self.word_dict[w] = word_num
                self.word_list.append(w)
                word_num += 1
                # print(word_temp_list[i])
            i += 1
    def predict(self, license_plate):
        plate = ""

        if len(license_plate.subrects) == 7:
            for index in range(3):
                character = license_plate.subrects[index]
                character_image = license_plate.image.crop(
                    Point(character.x, character.y),
                    Point(character.x + character.w - 1,
                          character.y + character.h - 1))

                if character_image.data.size > 0 and character_image.data is not None:
                    letter = self.letter_recognizer.predict(
                        character_image, True)

                    if isalpha(letter):
                        plate += letter
                    else:
                        plate += "a"
                else:
                    plate += "a"

            for index in range(3, 7):
                character = license_plate.subrects[index]
                character_image = license_plate.image.crop(
                    Point(character.x, character.y),
                    Point(character.x + character.w - 1,
                          character.y + character.h - 1))

                if character_image.data.size > 0 and character_image.data is not None:
                    digit = self.number_recognizer.predict(character_image)

                    if isdigit(digit):
                        plate += digit
                    else:
                        plate += str(1)
                else:
                    plate += str(1)

        else:
            plate = "AAA1111"

        return plate
Exemple #6
0
# /**
#  * @author [Limm-jk]
#  * @email [[email protected]]
#  * @create date 2020-04-13 15:46:31
#  * @modify date 2020-04-13 15:46:31
#  * @desc [description]
#  */

from numpy.core.defchararray import isdigit
import sys

poke_arr = []

x, y = map(int, sys.stdin.readline().split())

for _ in range(x):
    poke_arr.append(sys.stdin.readline().rstrip())

for _ in range(y):
    input1 = sys.stdin.readline().rstrip()
    if (isdigit(input1)):
        print(poke_arr[int(input1) - 1])

    else:
        print(poke_arr.index(input1) + 1)
Exemple #7
0
 license_plate = character_validator.adjust_characters(license_plate, image_original, image_width)
 correct_plate = config_data.license_plates_text
 index = 0
 
 for character in license_plate.subrects:
     index += 1
     
     character_image = license_plate.image.crop(Point(character.x, character.y), Point(character.x + character.w - 1, character.y + character.h - 1))
     
     if character_image.data.size > 0 and character_image.data is not None:
         image = Image(image=character_image.data)
         image = image.resize(200, 200)
         character = chr(image.plot())
         image = character_image.resize(character_original_width, character_original_height)
                     
         if isalpha(character) or isdigit(character):        
             if isalpha(character) or character == "1" or character == "0":
                 if character != "1" and character != "0":
                     letter_labels.append(ord(character))
                     letter_images.append(image.data.flatten())
                     print "Character: " + character
                 else:
                     if character == "1":
                         character = "i"
                         
                     if character == "0":
                         character = "o"
                         
                     letter_labels.append(ord(character))
                     letter_images.append(image.data.flatten())
                     print "Character: " + character
Exemple #8
0
    def writeIntoFile(self, outFilePath, similarContentDic):
        # 关联的数组的个数
        LinkedArraySize = len(similarContentDic)
        AllArrayDic = {}
        if self.kind == 0:
            kind_str = "one day"
        elif self.kind == 1:
            kind_str = "one hour"
        else:
            kind_str = "ten minutes"
        # 文件中的节点相连数组总个数
        AllArrayDic['LinkedArraySize'] = LinkedArraySize
        AllArrayDic['Date'] = self.window_date.strftime("%Y-%m-%d %H:%M:%S")
        AllArrayDic['TimeWindowLen'] = kind_str
        count_array = 1
        for i in similarContentDic:
            nodeSize = len(similarContentDic[i])
            AllNodeDic = {}
            keywords_list = []
            keywords_dict = {}
            # 一个数组的节点个数
            AllNodeDic['nodeSize'] = nodeSize
            count_node = 1
            # 得到所有节点名字的数组
            AllNodeNameArray = [str(data.username) for data in similarContentDic[i]]
            AllNodeDic['AllNodeNameArray'] = AllNodeNameArray
            for data in similarContentDic[i]:
                nodeAttr = 'node_' + str(count_node)
                ID = int(data.id)
                nodeName = str(data.username)
                # print(nodeName)

                # 去掉自身名字
                # linkedNodeNameArray = AllNodeNameArray.copy()
                # linkedNodeNameArray.remove(nodeName)
                nodeInfo = {}
                nodeDic = {}
                nodeDic['ID'] = ID
                nodeDic['nodeName'] = nodeName
                # nodeDic['linkedNodeNameArray'] = linkedNodeNameArray
                nodeDic['nodeInfo'] = nodeInfo

                # 将节点信息添加到字典中
                AllNodeDic[nodeAttr] = nodeDic
                count_node += 1

                # 提取题目关键词并将其加入keywords_dict字典中
                keynum = math.ceil(len(data.title) / 5)
                keywords = analyse.extract_tags(data.title, topK=keynum)
                # print(keynum)
                # print(keywords)
                for word_item in keywords:
                    if word_item in keywords_dict:
                        keywords_dict[word_item] += 2
                    else:
                        keywords_dict[word_item] = 2

                # 提取text关键词并将其加入keywords_dict字典中
                keynum = math.ceil(len(data.text) / 30)
                keywords = analyse.extract_tags(data.text, topK=keynum)
                # print(keynum)
                # print(keywords)
                for word_item in keywords:
                    if word_item in keywords_dict:
                        keywords_dict[word_item] += 1
                    else:
                        keywords_dict[word_item] = 1


            LinkedarrayAttr = 'LinkedArray_' + str(count_array)
            # 一个相连数组信息添加到字典
            AllArrayDic[LinkedarrayAttr] = AllNodeDic
            count_array += 1

            # 处理关键词字典
            keywords_temp_list = sorted(keywords_dict.items(), key=lambda item: item[1], reverse=True)  # 出来后是列表形式
            if len(keywords_temp_list) > 20:
                topnum = 10
            else:
                topnum = math.ceil(len(keywords_temp_list) / 2)

            # creat self.word_dict
            i = 0
            word_num = 0
            while word_num < topnum and i < len(keywords_temp_list):
                w = keywords_temp_list[i][0]
                if not isdigit(w) and w not in stopwords:
                    keywords_list.append(w)
                    word_num += 1
                    # print(keywords_temp_list[i])
                i += 1
            AllNodeDic['keywords'] = keywords_list


        # 写入文件
        with open(outFilePath, 'w', encoding='utf-8') as file_object:
            json.dump(AllArrayDic, file_object, ensure_ascii=False, indent=4)
            file_object.close()
  logger.log(Logger.INFO, "Loading images to train classifiers.")
 
  number_images = np.loadtxt(path_number_images, np.uint8)
  number_labels = np.loadtxt(path_number_labels, np.float32)
  number_labels = number_labels.reshape((number_labels.size, 1))                
  converted_images = []
  labels = []
  
  for index in range(len(number_images)):
      image = number_images[index]
      reshaped = Image(image=image.reshape((character_original_height, character_original_width)))
      reshaped.binarize(adaptative=True)
      mean_value = np.mean(reshaped.data)
      
      if mean_value < 220:
          if isdigit(chr(int(number_labels[index]))):
              converted_images.append(reshaped)
              labels.append(number_labels[index])
                        
  number_images = converted_images
  number_labels = labels
  
  letter_images = np.loadtxt(path_letter_images, np.uint8)
  letter_labels = np.loadtxt(path_letter_labels, np.float32)
  letter_labels = letter_labels.reshape((letter_labels.size, 1))
  converted_images_l = []
  labels_l = []
  
  for index in range(len(letter_images)):
      image = letter_images[index]
      reshaped = Image(image=image.reshape((character_original_height, character_original_width)))
Exemple #10
0
def ans(img):
    pin = []
    # image = cv2.imread(img, cv2.IMREAD_COLOR)
    image = img
    gray = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2GRAY)
    gray = cv2.fastNlMeansDenoising(gray,  100, 10, 7, 21)
    ret, th = cv2.threshold(
        gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

    contours = cv2.findContours(
        th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]

    contours = sorted(contours, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(
        ctr)[2] + (cv2.boundingRect(ctr)[1] + cv2.boundingRect(ctr)[3]))

    for cnt in contours:
        x, y, w, h = cv2.boundingRect(cnt)

        if h < 40:
            continue

        digit = th[y:y + h, x:x + w]

        resized_digit = cv2.resize(digit, (18, 18))

        padded_digit = np.pad(resized_digit, ((5, 5), (5, 5)),
                              "constant", constant_values=0)

        digit = padded_digit.reshape(1, 28, 28, 1)
        digit = digit / 255.0

        pred1 = model1.predict([digit])[0]
        pred2 = model2.predict([digit])[0]

        final_pred1 = np.argmax(pred1)
        final_pred2 = np.argmax(pred2)

        final_pred = final_pred2 if max(
            pred1)*1.5 < max(pred2) else final_pred1

        pred = int(max(max(pred1), max(pred2)) * 100)

        if isdigit(chr(ascii_map[int(final_pred)])) or chr(ascii_map[int(final_pred)]) in ['O', 'o', 'I', '|', "T"]:

            num = chr(ascii_map[int(final_pred)])
            num = '0' if num in ['O', 'o'] else num
            num = '1' if num in ['|', 'I'] else num
            num = '7' if num in ["T"] else num

            data = num + " " + str(int(pred)) + '%'
            cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 1)

            font = cv2.FONT_HERSHEY_SIMPLEX
            fontScale = 0.5
            color = (255, 0, 0)
            thickness = 1

            cv2.putText(image, data, (x, y - 5), font,
                        fontScale, color, thickness)

            pin.append(num)

            # print(data)

        # cv2.imshow('Predictions', image)
        # cv2.waitKey(0)

    return pin[-6::]