Python Wordsearch:如何打印找到的单词并将其他字母转换为感叹号?

2024-10-06 12:19:02 发布

您现在位置:Python中文网/ 问答频道 /正文

使用这样的测试文件:

hfhfdhjkayuwe
cmnzgdsoifoid
skjhfbskjfhkhsdj
smjbfjkshfsjfhk
sjhfhsfkjhsfkjlfjsl
qwuaoirhdfbjkak
kjfaheuiwopfakjh
sweetfoodislife
kjhfsiuskjhlawrpof
sfkjzaljifopwesdhj

我如何修复代码,使其在对角、水平、垂直、左右、前后搜索单词,当它找到用户输入的单词时,它打印出网格,显示找到该单词的位置,并将每隔一个字符转换为感叹号?例如,对于上面的测试文件,如果用户输入“sweetfoodislife”,我希望我的代码输出以下内容:

!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
Sweetfoodislife
!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!

我只是想知道如何将每个字母转换成感叹号,除了用户输入的单词find。如果找不到该单词,则输出应生成“我找不到该单词”

我有下面的代码,但它在第12行产生了一个错误,称列表索引超出范围

def grid():
    filename = input(“Enter name of test file:”)
    word = input("What word are you searching: ")
    file = open(filename, 'r').readlines()
    with open(filename, 'w') as file_2:
        for item in file:
           print("!", item) 
    a = len(word)
    b = len(word[0])
    for i in range(a):
        for j in range(b):
            if file[0] == word[i][j]:
                if word in file[i][j]:
                    print(open(filename).read())
    print("I can’t find this word")

网格()


Tags: 文件代码用户in网格foropenfind
1条回答
网友
1楼 · 发布于 2024-10-06 12:19:02

鉴于:

txt='''\
hfhfdhjkayuwe
cmnzgdsoifoid
skjhfbskjfhkhsdj
smjbfjkshfsjfhk
sjhfhsfkjhsfkjlfjsl
qwuaoirhdfbjkak
kjfaheuiwopfakjh
sweetfoodislife
kjhfsiuskjhlawrpof
sfkjzaljifopwesdhj'''

tgt='sweetfoodislife'

你可以做:

print('\n'.join([line if line==tgt else '!'*len(line)  for line in txt.splitlines()]))

印刷品:

!!!!!!!!!!!!!
!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!
sweetfoodislife
!!!!!!!!!!!!!!!!!!
!!!!!!!!!!!!!!!!!!

相关问题 更多 >