1

第一次在这里发帖。

基本上我有一个充满词汇的.txt。我设法将 .txt 中的词汇单词拆分为 python 文件中的列表。我想让第一个“:”之前的每个列表元素中的字符串为粗体,然后列表元素中的所有内容为常规。我已经找到了如何使文本加粗以及如何使其正常化。但是,我正在努力如何让 Python 中的程序遍历每个列表元素,使第一个“:”之前的内容变粗?

这是我到目前为止所得到的:

class style:
    BOLD = "\033[1m"
    END = "\033[0m"

def Convert(string):
    li = list(string.split("\n\n"))
    return li
  
print (style.BOLD + "My super cool text" + style.END)

vocablist = ('''to remind s.o. (of sth./to do sth.): to put in mind of something: cause to remember

to remember sth.: to retain in the memory

to reject: to refuse to accept, hear, receive, or admit

to affirm: to assert as valid or confirmed; to show or express a strong belief in

universality: the quality of being true in or appropriate for all situations.

bias: a personal and sometimes unreasoned judgment; prejudice

implicit: present but not consciously held or recognized

conscious: perceiving or noticing with a degree of controlled thought or observation

assumption: an assuming that something is true

mundane: everyday, ordinary, routine

convention: usage or custom especially in social matters; an established practice

unconscious: not knowing or perceiving : not aware

normative: conforming to or based on norms OR dictating norms

imaginative: of, relating to, or characterized by imagination OR without truth

deviation: noticeable or marked departure from accepted norms

omnipresent: present in all places at all times

omnipotent: having virtually unlimited authority or influence; all-powerful
''')
    
print(Convert(vocablist))
for i in vocablist:
    newlist = list.append(style.BOLD + vocablist[i])
    if ":" in vocablist[i]:
        newlist[i] + style.END
    i+=1
4

2 回答 2

0

几件事:

  1. 列表追加不是那样调用的。如果列表被命名为 mylist,你可以这样做: mylist.append(new_element),并且它就地修改(不返回值)
  2. 您需要分隔行的不同部分,以便对它们应用不同的格式。你可以用split这个
  3. 该构造for i in vocablist意味着 i 是来自 vocablist 的元素,而不是整数。
converted_list = Convert(vocablist)
formatted_list = []
for line in converted_list:
    if len(line) == 0:
        continue
    word, defn = line.split(":", 1)
    new_line = style.BOLD + word + ":" + style.END + defn
    formatted_list.append(new_line)
print(formatted_list)
于 2021-10-08T13:23:08.793 回答
0

您必须在该字符串中解决一些约定并使用正则表达式。

import re

示例 1:

bolded_fragments1 = re.sub(r'([A-z]*)(?=:){1}', style.BOLD+r'\1'+style.END,vocablist)
print(bolded_fragments1)

“:”之前的粗体字母单词

示例 2:

bolded_fragments2 = re.sub(r'(.*)(?=:){1}', style.BOLD+r'\1'+style.END,vocablist)
print(bolded_fragments2)

在“:”之前加粗整行

于 2021-10-08T13:18:22.143 回答